]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_session/src/filesearch.rs
Auto merge of #85448 - nanguye2496:nanguye2496/debuginfo_tests, r=Mark-Simulacrum
[rust.git] / compiler / rustc_session / src / filesearch.rs
1 pub use self::FileMatch::*;
2
3 use std::env;
4 use std::fs;
5 use std::path::{Path, PathBuf};
6
7 use crate::search_paths::{PathKind, SearchPath, SearchPathFile};
8 use rustc_fs_util::fix_windows_verbatim_for_gcc;
9 use tracing::debug;
10
11 #[derive(Copy, Clone)]
12 pub enum FileMatch {
13     FileMatches,
14     FileDoesntMatch,
15 }
16
17 // A module for searching for libraries
18
19 #[derive(Clone)]
20 pub struct FileSearch<'a> {
21     sysroot: &'a Path,
22     triple: &'a str,
23     search_paths: &'a [SearchPath],
24     tlib_path: &'a SearchPath,
25     kind: PathKind,
26 }
27
28 impl<'a> FileSearch<'a> {
29     pub fn search_paths(&self) -> impl Iterator<Item = &'a SearchPath> {
30         let kind = self.kind;
31         self.search_paths
32             .iter()
33             .filter(move |sp| sp.kind.matches(kind))
34             .chain(std::iter::once(self.tlib_path))
35     }
36
37     pub fn get_lib_path(&self) -> PathBuf {
38         make_target_lib_path(self.sysroot, self.triple)
39     }
40
41     pub fn get_self_contained_lib_path(&self) -> PathBuf {
42         self.get_lib_path().join("self-contained")
43     }
44
45     pub fn search<F>(&self, mut pick: F)
46     where
47         F: FnMut(&SearchPathFile, PathKind) -> FileMatch,
48     {
49         for search_path in self.search_paths() {
50             debug!("searching {}", search_path.dir.display());
51             fn is_rlib(spf: &SearchPathFile) -> bool {
52                 if let Some(f) = &spf.file_name_str { f.ends_with(".rlib") } else { false }
53             }
54             // Reading metadata out of rlibs is faster, and if we find both
55             // an rlib and a dylib we only read one of the files of
56             // metadata, so in the name of speed, bring all rlib files to
57             // the front of the search list.
58             let files1 = search_path.files.iter().filter(|spf| is_rlib(&spf));
59             let files2 = search_path.files.iter().filter(|spf| !is_rlib(&spf));
60             for spf in files1.chain(files2) {
61                 debug!("testing {}", spf.path.display());
62                 let maybe_picked = pick(spf, search_path.kind);
63                 match maybe_picked {
64                     FileMatches => {
65                         debug!("picked {}", spf.path.display());
66                     }
67                     FileDoesntMatch => {
68                         debug!("rejected {}", spf.path.display());
69                     }
70                 }
71             }
72         }
73     }
74
75     pub fn new(
76         sysroot: &'a Path,
77         triple: &'a str,
78         search_paths: &'a [SearchPath],
79         tlib_path: &'a SearchPath,
80         kind: PathKind,
81     ) -> FileSearch<'a> {
82         debug!("using sysroot = {}, triple = {}", sysroot.display(), triple);
83         FileSearch { sysroot, triple, search_paths, tlib_path, kind }
84     }
85
86     // Returns just the directories within the search paths.
87     pub fn search_path_dirs(&self) -> Vec<PathBuf> {
88         self.search_paths().map(|sp| sp.dir.to_path_buf()).collect()
89     }
90
91     // Returns a list of directories where target-specific tool binaries are located.
92     pub fn get_tools_search_paths(&self, self_contained: bool) -> Vec<PathBuf> {
93         let rustlib_path = rustc_target::target_rustlib_path(self.sysroot, &self.triple);
94         let p = std::array::IntoIter::new([
95             Path::new(&self.sysroot),
96             Path::new(&rustlib_path),
97             Path::new("bin"),
98         ])
99         .collect::<PathBuf>();
100         if self_contained { vec![p.clone(), p.join("self-contained")] } else { vec![p] }
101     }
102 }
103
104 pub fn make_target_lib_path(sysroot: &Path, target_triple: &str) -> PathBuf {
105     let rustlib_path = rustc_target::target_rustlib_path(sysroot, target_triple);
106     std::array::IntoIter::new([sysroot, Path::new(&rustlib_path), Path::new("lib")])
107         .collect::<PathBuf>()
108 }
109
110 // This function checks if sysroot is found using env::args().next(), and if it
111 // is not found, uses env::current_exe() to imply sysroot.
112 pub fn get_or_default_sysroot() -> PathBuf {
113     // Follow symlinks.  If the resolved path is relative, make it absolute.
114     fn canonicalize(path: PathBuf) -> PathBuf {
115         let path = fs::canonicalize(&path).unwrap_or(path);
116         // See comments on this target function, but the gist is that
117         // gcc chokes on verbatim paths which fs::canonicalize generates
118         // so we try to avoid those kinds of paths.
119         fix_windows_verbatim_for_gcc(&path)
120     }
121
122     // Use env::current_exe() to get the path of the executable following
123     // symlinks/canonicalizing components.
124     fn from_current_exe() -> PathBuf {
125         match env::current_exe() {
126             Ok(exe) => {
127                 let mut p = canonicalize(exe);
128                 p.pop();
129                 p.pop();
130                 p
131             }
132             Err(e) => panic!("failed to get current_exe: {}", e),
133         }
134     }
135
136     // Use env::args().next() to get the path of the executable without
137     // following symlinks/canonicalizing any component. This makes the rustc
138     // binary able to locate Rust libraries in systems using content-addressable
139     // storage (CAS).
140     fn from_env_args_next() -> Option<PathBuf> {
141         match env::args_os().next() {
142             Some(first_arg) => {
143                 let mut p = PathBuf::from(first_arg);
144
145                 // Check if sysroot is found using env::args().next() only if the rustc in argv[0]
146                 // is a symlink (see #79253). We might want to change/remove it to conform with
147                 // https://www.gnu.org/prep/standards/standards.html#Finding-Program-Files in the
148                 // future.
149                 if fs::read_link(&p).is_err() {
150                     // Path is not a symbolic link or does not exist.
151                     return None;
152                 }
153
154                 // Pop off `bin/rustc`, obtaining the suspected sysroot.
155                 p.pop();
156                 p.pop();
157                 // Look for the target rustlib directory in the suspected sysroot.
158                 let mut rustlib_path = rustc_target::target_rustlib_path(&p, "dummy");
159                 rustlib_path.pop(); // pop off the dummy target.
160                 if rustlib_path.exists() { Some(p) } else { None }
161             }
162             None => None,
163         }
164     }
165
166     // Check if sysroot is found using env::args().next(), and if is not found,
167     // use env::current_exe() to imply sysroot.
168     from_env_args_next().unwrap_or_else(from_current_exe)
169 }