1 //! Loads "sysroot" crate.
2 //!
3 //! One confusing point here is that normally sysroot is a bunch of `.rlib`s,
4 //! but we can't process `.rlib` and need source code instead. The source code
5 //! is typically installed with `rustup component add rust-src` command.
6 
7 use std::{env, fs, iter, ops, path::PathBuf, process::Command};
8 
9 use anyhow::{format_err, Result};
10 use la_arena::{Arena, Idx};
11 use paths::{AbsPath, AbsPathBuf};
12 
13 use crate::{utf8_stdout, ManifestPath};
14 
15 #[derive(Debug, Clone, Eq, PartialEq)]
16 pub struct Sysroot {
17     root: AbsPathBuf,
18     crates: Arena<SysrootCrateData>,
19 }
20 
21 pub(crate) type SysrootCrate = Idx<SysrootCrateData>;
22 
23 #[derive(Debug, Clone, Eq, PartialEq)]
24 pub struct SysrootCrateData {
25     pub name: String,
26     pub root: ManifestPath,
27     pub deps: Vec<SysrootCrate>,
28 }
29 
30 impl ops::Index<SysrootCrate> for Sysroot {
31     type Output = SysrootCrateData;
index(&self, index: SysrootCrate) -> &SysrootCrateData32     fn index(&self, index: SysrootCrate) -> &SysrootCrateData {
33         &self.crates[index]
34     }
35 }
36 
37 impl Sysroot {
root(&self) -> &AbsPath38     pub fn root(&self) -> &AbsPath {
39         &self.root
40     }
41 
public_deps(&self) -> impl Iterator<Item = (&'static str, SysrootCrate, bool)> + '_42     pub fn public_deps(&self) -> impl Iterator<Item = (&'static str, SysrootCrate, bool)> + '_ {
43         // core is added as a dependency before std in order to
44         // mimic rustcs dependency order
45         ["core", "alloc", "std"]
46             .into_iter()
47             .zip(iter::repeat(true))
48             .chain(iter::once(("test", false)))
49             .filter_map(move |(name, prelude)| Some((name, self.by_name(name)?, prelude)))
50     }
51 
proc_macro(&self) -> Option<SysrootCrate>52     pub fn proc_macro(&self) -> Option<SysrootCrate> {
53         self.by_name("proc_macro")
54     }
55 
crates<'a>(&'a self) -> impl Iterator<Item = SysrootCrate> + ExactSizeIterator + 'a56     pub fn crates<'a>(&'a self) -> impl Iterator<Item = SysrootCrate> + ExactSizeIterator + 'a {
57         self.crates.iter().map(|(id, _data)| id)
58     }
59 
discover(dir: &AbsPath) -> Result<Sysroot>60     pub fn discover(dir: &AbsPath) -> Result<Sysroot> {
61         tracing::debug!("Discovering sysroot for {}", dir.display());
62         let sysroot_dir = discover_sysroot_dir(dir)?;
63         let sysroot_src_dir = discover_sysroot_src_dir(&sysroot_dir, dir)?;
64         let res = Sysroot::load(sysroot_src_dir)?;
65         Ok(res)
66     }
67 
discover_rustc(cargo_toml: &ManifestPath) -> Option<ManifestPath>68     pub fn discover_rustc(cargo_toml: &ManifestPath) -> Option<ManifestPath> {
69         tracing::debug!("Discovering rustc source for {}", cargo_toml.display());
70         let current_dir = cargo_toml.parent();
71         discover_sysroot_dir(current_dir).ok().and_then(|sysroot_dir| get_rustc_src(&sysroot_dir))
72     }
73 
load(sysroot_src_dir: AbsPathBuf) -> Result<Sysroot>74     pub fn load(sysroot_src_dir: AbsPathBuf) -> Result<Sysroot> {
75         let mut sysroot = Sysroot { root: sysroot_src_dir, crates: Arena::default() };
76 
77         for path in SYSROOT_CRATES.trim().lines() {
78             let name = path.split('/').last().unwrap();
79             let root = [format!("{}/src/lib.rs", path), format!("lib{}/lib.rs", path)]
80                 .into_iter()
81                 .map(|it| sysroot.root.join(it))
82                 .filter_map(|it| ManifestPath::try_from(it).ok())
83                 .find(|it| fs::metadata(it).is_ok());
84 
85             if let Some(root) = root {
86                 sysroot.crates.alloc(SysrootCrateData {
87                     name: name.into(),
88                     root,
89                     deps: Vec::new(),
90                 });
91             }
92         }
93 
94         if let Some(std) = sysroot.by_name("std") {
95             for dep in STD_DEPS.trim().lines() {
96                 if let Some(dep) = sysroot.by_name(dep) {
97                     sysroot.crates[std].deps.push(dep)
98                 }
99             }
100         }
101 
102         if let Some(alloc) = sysroot.by_name("alloc") {
103             if let Some(core) = sysroot.by_name("core") {
104                 sysroot.crates[alloc].deps.push(core);
105             }
106         }
107 
108         if let Some(proc_macro) = sysroot.by_name("proc_macro") {
109             if let Some(std) = sysroot.by_name("std") {
110                 sysroot.crates[proc_macro].deps.push(std);
111             }
112         }
113 
114         if sysroot.by_name("core").is_none() {
115             let var_note = if env::var_os("RUST_SRC_PATH").is_some() {
116                 " (`RUST_SRC_PATH` might be incorrect, try unsetting it)"
117             } else {
118                 ""
119             };
120             anyhow::bail!(
121                 "could not find libcore in sysroot path `{}`{}",
122                 sysroot.root.as_path().display(),
123                 var_note,
124             );
125         }
126 
127         Ok(sysroot)
128     }
129 
by_name(&self, name: &str) -> Option<SysrootCrate>130     fn by_name(&self, name: &str) -> Option<SysrootCrate> {
131         let (id, _data) = self.crates.iter().find(|(_id, data)| data.name == name)?;
132         Some(id)
133     }
134 }
135 
discover_sysroot_dir(current_dir: &AbsPath) -> Result<AbsPathBuf>136 fn discover_sysroot_dir(current_dir: &AbsPath) -> Result<AbsPathBuf> {
137     let mut rustc = Command::new(toolchain::rustc());
138     rustc.current_dir(current_dir).args(&["--print", "sysroot"]);
139     tracing::debug!("Discovering sysroot by {:?}", rustc);
140     let stdout = utf8_stdout(rustc)?;
141     Ok(AbsPathBuf::assert(PathBuf::from(stdout)))
142 }
143 
discover_sysroot_src_dir( sysroot_path: &AbsPathBuf, current_dir: &AbsPath, ) -> Result<AbsPathBuf>144 fn discover_sysroot_src_dir(
145     sysroot_path: &AbsPathBuf,
146     current_dir: &AbsPath,
147 ) -> Result<AbsPathBuf> {
148     if let Ok(path) = env::var("RUST_SRC_PATH") {
149         let path = AbsPathBuf::try_from(path.as_str())
150             .map_err(|path| format_err!("RUST_SRC_PATH must be absolute: {}", path.display()))?;
151         let core = path.join("core");
152         if fs::metadata(&core).is_ok() {
153             tracing::debug!("Discovered sysroot by RUST_SRC_PATH: {}", path.display());
154             return Ok(path);
155         }
156         tracing::debug!("RUST_SRC_PATH is set, but is invalid (no core: {:?}), ignoring", core);
157     }
158 
159     get_rust_src(sysroot_path)
160         .or_else(|| {
161             let mut rustup = Command::new(toolchain::rustup());
162             rustup.current_dir(current_dir).args(&["component", "add", "rust-src"]);
163             utf8_stdout(rustup).ok()?;
164             get_rust_src(sysroot_path)
165         })
166         .ok_or_else(|| {
167             format_err!(
168                 "\
169 can't load standard library from sysroot
170 {}
171 (discovered via `rustc --print sysroot`)
172 try installing the Rust source the same way you installed rustc",
173                 sysroot_path.display(),
174             )
175         })
176 }
177 
get_rustc_src(sysroot_path: &AbsPath) -> Option<ManifestPath>178 fn get_rustc_src(sysroot_path: &AbsPath) -> Option<ManifestPath> {
179     let rustc_src = sysroot_path.join("lib/rustlib/rustc-src/rust/compiler/rustc/Cargo.toml");
180     let rustc_src = ManifestPath::try_from(rustc_src).ok()?;
181     tracing::debug!("Checking for rustc source code: {}", rustc_src.display());
182     if fs::metadata(&rustc_src).is_ok() {
183         Some(rustc_src)
184     } else {
185         None
186     }
187 }
188 
get_rust_src(sysroot_path: &AbsPath) -> Option<AbsPathBuf>189 fn get_rust_src(sysroot_path: &AbsPath) -> Option<AbsPathBuf> {
190     let rust_src = sysroot_path.join("lib/rustlib/src/rust/library");
191     tracing::debug!("Checking sysroot: {}", rust_src.display());
192     if fs::metadata(&rust_src).is_ok() {
193         Some(rust_src)
194     } else {
195         None
196     }
197 }
198 
199 const SYSROOT_CRATES: &str = "
200 alloc
201 core
202 panic_abort
203 panic_unwind
204 proc_macro
205 profiler_builtins
206 std
207 stdarch/crates/std_detect
208 term
209 test
210 unwind";
211 
212 const STD_DEPS: &str = "
213 alloc
214 core
215 panic_abort
216 panic_unwind
217 profiler_builtins
218 std_detect
219 term
220 test
221 unwind";
222