]> git.lizzy.rs Git - rust.git/blob - src/librustc_session/filesearch.rs
Rollup merge of #72688 - djugei:master, r=Amanieu
[rust.git] / src / librustc_session / filesearch.rs
1 #![allow(non_camel_case_types)]
2
3 pub use self::FileMatch::*;
4
5 use std::borrow::Cow;
6 use std::env;
7 use std::fs;
8 use std::path::{Path, PathBuf};
9
10 use crate::search_paths::{PathKind, SearchPath, SearchPathFile};
11 use log::debug;
12 use rustc_fs_util::fix_windows_verbatim_for_gcc;
13
14 #[derive(Copy, Clone)]
15 pub enum FileMatch {
16     FileMatches,
17     FileDoesntMatch,
18 }
19
20 // A module for searching for libraries
21
22 #[derive(Clone)]
23 pub struct FileSearch<'a> {
24     sysroot: &'a Path,
25     triple: &'a str,
26     search_paths: &'a [SearchPath],
27     tlib_path: &'a SearchPath,
28     kind: PathKind,
29 }
30
31 impl<'a> FileSearch<'a> {
32     pub fn search_paths(&self) -> impl Iterator<Item = &'a SearchPath> {
33         let kind = self.kind;
34         self.search_paths
35             .iter()
36             .filter(move |sp| sp.kind.matches(kind))
37             .chain(std::iter::once(self.tlib_path))
38     }
39
40     pub fn get_lib_path(&self) -> PathBuf {
41         make_target_lib_path(self.sysroot, self.triple)
42     }
43
44     pub fn get_self_contained_lib_path(&self) -> PathBuf {
45         self.get_lib_path().join("self-contained")
46     }
47
48     pub fn search<F>(&self, mut pick: F)
49     where
50         F: FnMut(&SearchPathFile, PathKind) -> FileMatch,
51     {
52         for search_path in self.search_paths() {
53             debug!("searching {}", search_path.dir.display());
54             fn is_rlib(spf: &SearchPathFile) -> bool {
55                 if let Some(f) = &spf.file_name_str { f.ends_with(".rlib") } else { false }
56             }
57             // Reading metadata out of rlibs is faster, and if we find both
58             // an rlib and a dylib we only read one of the files of
59             // metadata, so in the name of speed, bring all rlib files to
60             // the front of the search list.
61             let files1 = search_path.files.iter().filter(|spf| is_rlib(&spf));
62             let files2 = search_path.files.iter().filter(|spf| !is_rlib(&spf));
63             for spf in files1.chain(files2) {
64                 debug!("testing {}", spf.path.display());
65                 let maybe_picked = pick(spf, search_path.kind);
66                 match maybe_picked {
67                     FileMatches => {
68                         debug!("picked {}", spf.path.display());
69                     }
70                     FileDoesntMatch => {
71                         debug!("rejected {}", spf.path.display());
72                     }
73                 }
74             }
75         }
76     }
77
78     pub fn new(
79         sysroot: &'a Path,
80         triple: &'a str,
81         search_paths: &'a Vec<SearchPath>,
82         tlib_path: &'a SearchPath,
83         kind: PathKind,
84     ) -> FileSearch<'a> {
85         debug!("using sysroot = {}, triple = {}", sysroot.display(), triple);
86         FileSearch { sysroot, triple, search_paths, tlib_path, kind }
87     }
88
89     // Returns just the directories within the search paths.
90     pub fn search_path_dirs(&self) -> Vec<PathBuf> {
91         self.search_paths().map(|sp| sp.dir.to_path_buf()).collect()
92     }
93
94     // Returns a list of directories where target-specific tool binaries are located.
95     pub fn get_tools_search_paths(&self, self_contained: bool) -> Vec<PathBuf> {
96         let mut p = PathBuf::from(self.sysroot);
97         p.push(find_libdir(self.sysroot).as_ref());
98         p.push(RUST_LIB_DIR);
99         p.push(&self.triple);
100         p.push("bin");
101         if self_contained { vec![p.clone(), p.join("self-contained")] } else { vec![p.clone()] }
102     }
103 }
104
105 pub fn relative_target_lib_path(sysroot: &Path, target_triple: &str) -> PathBuf {
106     let mut p = PathBuf::from(find_libdir(sysroot).as_ref());
107     assert!(p.is_relative());
108     p.push(RUST_LIB_DIR);
109     p.push(target_triple);
110     p.push("lib");
111     p
112 }
113
114 pub fn make_target_lib_path(sysroot: &Path, target_triple: &str) -> PathBuf {
115     sysroot.join(&relative_target_lib_path(sysroot, target_triple))
116 }
117
118 pub fn get_or_default_sysroot() -> PathBuf {
119     // Follow symlinks.  If the resolved path is relative, make it absolute.
120     fn canonicalize(path: Option<PathBuf>) -> Option<PathBuf> {
121         path.and_then(|path| {
122             match fs::canonicalize(&path) {
123                 // See comments on this target function, but the gist is that
124                 // gcc chokes on verbatim paths which fs::canonicalize generates
125                 // so we try to avoid those kinds of paths.
126                 Ok(canon) => Some(fix_windows_verbatim_for_gcc(&canon)),
127                 Err(e) => panic!("failed to get realpath: {}", e),
128             }
129         })
130     }
131
132     match env::current_exe() {
133         Ok(exe) => match canonicalize(Some(exe)) {
134             Some(mut p) => {
135                 p.pop();
136                 p.pop();
137                 p
138             }
139             None => panic!("can't determine value for sysroot"),
140         },
141         Err(ref e) => panic!(format!("failed to get current_exe: {}", e)),
142     }
143 }
144
145 // The name of the directory rustc expects libraries to be located.
146 fn find_libdir(sysroot: &Path) -> Cow<'static, str> {
147     // FIXME: This is a quick hack to make the rustc binary able to locate
148     // Rust libraries in Linux environments where libraries might be installed
149     // to lib64/lib32. This would be more foolproof by basing the sysroot off
150     // of the directory where `librustc_driver` is located, rather than
151     // where the rustc binary is.
152     // If --libdir is set during configuration to the value other than
153     // "lib" (i.e., non-default), this value is used (see issue #16552).
154
155     #[cfg(target_pointer_width = "64")]
156     const PRIMARY_LIB_DIR: &str = "lib64";
157
158     #[cfg(target_pointer_width = "32")]
159     const PRIMARY_LIB_DIR: &str = "lib32";
160
161     const SECONDARY_LIB_DIR: &str = "lib";
162
163     match option_env!("CFG_LIBDIR_RELATIVE") {
164         Some(libdir) if libdir != "lib" => libdir.into(),
165         _ => {
166             if sysroot.join(PRIMARY_LIB_DIR).join(RUST_LIB_DIR).exists() {
167                 PRIMARY_LIB_DIR.into()
168             } else {
169                 SECONDARY_LIB_DIR.into()
170             }
171         }
172     }
173 }
174
175 // The name of rustc's own place to organize libraries.
176 // Used to be "rustc", now the default is "rustlib"
177 const RUST_LIB_DIR: &str = "rustlib";