]> git.lizzy.rs Git - rust.git/blob - src/librustc/metadata/filesearch.rs
cc67f3ddf0330af6f9141a2620b6a7e403d902f2
[rust.git] / src / librustc / metadata / filesearch.rs
1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 #![allow(non_camel_case_types)]
12
13 pub use self::FileMatch::*;
14
15 use std::collections::HashSet;
16 use std::io::fs::PathExtensions;
17 use std::io::fs;
18 use std::os;
19
20 use util::fs as myfs;
21 use session::search_paths::{SearchPaths, PathKind};
22
23 #[deriving(Copy)]
24 pub enum FileMatch {
25     FileMatches,
26     FileDoesntMatch,
27 }
28
29 // A module for searching for libraries
30 // FIXME (#2658): I'm not happy how this module turned out. Should
31 // probably just be folded into cstore.
32
33 /// Functions with type `pick` take a parent directory as well as
34 /// a file found in that directory.
35 pub type pick<'a> = |path: &Path|: 'a -> FileMatch;
36
37 pub struct FileSearch<'a> {
38     pub sysroot: &'a Path,
39     pub search_paths: &'a SearchPaths,
40     pub triple: &'a str,
41     pub kind: PathKind,
42 }
43
44 impl<'a> FileSearch<'a> {
45     pub fn for_each_lib_search_path<F>(&self, mut f: F) where
46         F: FnMut(&Path) -> FileMatch,
47     {
48         let mut visited_dirs = HashSet::new();
49         let mut found = false;
50
51         for path in self.search_paths.iter(self.kind) {
52             match f(path) {
53                 FileMatches => found = true,
54                 FileDoesntMatch => ()
55             }
56             visited_dirs.insert(path.as_vec().to_vec());
57         }
58
59         debug!("filesearch: searching lib path");
60         let tlib_path = make_target_lib_path(self.sysroot,
61                                     self.triple);
62         if !visited_dirs.contains(tlib_path.as_vec()) {
63             match f(&tlib_path) {
64                 FileMatches => found = true,
65                 FileDoesntMatch => ()
66             }
67         }
68
69         visited_dirs.insert(tlib_path.as_vec().to_vec());
70         // Try RUST_PATH
71         if !found {
72             let rustpath = rust_path();
73             for path in rustpath.iter() {
74                 let tlib_path = make_rustpkg_lib_path(
75                     self.sysroot, path, self.triple);
76                 debug!("is {} in visited_dirs? {}", tlib_path.display(),
77                         visited_dirs.contains(&tlib_path.as_vec().to_vec()));
78
79                 if !visited_dirs.contains(tlib_path.as_vec()) {
80                     visited_dirs.insert(tlib_path.as_vec().to_vec());
81                     // Don't keep searching the RUST_PATH if one match turns up --
82                     // if we did, we'd get a "multiple matching crates" error
83                     match f(&tlib_path) {
84                        FileMatches => {
85                            break;
86                        }
87                        FileDoesntMatch => ()
88                     }
89                 }
90             }
91         }
92     }
93
94     pub fn get_lib_path(&self) -> Path {
95         make_target_lib_path(self.sysroot, self.triple)
96     }
97
98     pub fn search(&self, pick: pick) {
99         self.for_each_lib_search_path(|lib_search_path| {
100             debug!("searching {}", lib_search_path.display());
101             match fs::readdir(lib_search_path) {
102                 Ok(files) => {
103                     let mut rslt = FileDoesntMatch;
104                     fn is_rlib(p: & &Path) -> bool {
105                         p.extension_str() == Some("rlib")
106                     }
107                     // Reading metadata out of rlibs is faster, and if we find both
108                     // an rlib and a dylib we only read one of the files of
109                     // metadata, so in the name of speed, bring all rlib files to
110                     // the front of the search list.
111                     let files1 = files.iter().filter(|p| is_rlib(p));
112                     let files2 = files.iter().filter(|p| !is_rlib(p));
113                     for path in files1.chain(files2) {
114                         debug!("testing {}", path.display());
115                         let maybe_picked = pick(path);
116                         match maybe_picked {
117                             FileMatches => {
118                                 debug!("picked {}", path.display());
119                                 rslt = FileMatches;
120                             }
121                             FileDoesntMatch => {
122                                 debug!("rejected {}", path.display());
123                             }
124                         }
125                     }
126                     rslt
127                 }
128                 Err(..) => FileDoesntMatch,
129             }
130         });
131     }
132
133     pub fn new(sysroot: &'a Path,
134                triple: &'a str,
135                search_paths: &'a SearchPaths,
136                kind: PathKind) -> FileSearch<'a> {
137         debug!("using sysroot = {}, triple = {}", sysroot.display(), triple);
138         FileSearch {
139             sysroot: sysroot,
140             search_paths: search_paths,
141             triple: triple,
142             kind: kind,
143         }
144     }
145
146     // Returns a list of directories where target-specific dylibs might be located.
147     pub fn get_dylib_search_paths(&self) -> Vec<Path> {
148         let mut paths = Vec::new();
149         self.for_each_lib_search_path(|lib_search_path| {
150             paths.push(lib_search_path.clone());
151             FileDoesntMatch
152         });
153         paths
154     }
155
156     // Returns a list of directories where target-specific tool binaries are located.
157     pub fn get_tools_search_paths(&self) -> Vec<Path> {
158         let mut p = Path::new(self.sysroot);
159         p.push(find_libdir(self.sysroot));
160         p.push(rustlibdir());
161         p.push(self.triple);
162         p.push("bin");
163         vec![p]
164     }
165 }
166
167 pub fn relative_target_lib_path(sysroot: &Path, target_triple: &str) -> Path {
168     let mut p = Path::new(find_libdir(sysroot));
169     assert!(p.is_relative());
170     p.push(rustlibdir());
171     p.push(target_triple);
172     p.push("lib");
173     p
174 }
175
176 fn make_target_lib_path(sysroot: &Path,
177                         target_triple: &str) -> Path {
178     sysroot.join(&relative_target_lib_path(sysroot, target_triple))
179 }
180
181 fn make_rustpkg_lib_path(sysroot: &Path,
182                          dir: &Path,
183                          triple: &str) -> Path {
184     let mut p = dir.join(find_libdir(sysroot));
185     p.push(triple);
186     p
187 }
188
189 pub fn get_or_default_sysroot() -> Path {
190     // Follow symlinks.  If the resolved path is relative, make it absolute.
191     fn canonicalize(path: Option<Path>) -> Option<Path> {
192         path.and_then(|path|
193             match myfs::realpath(&path) {
194                 Ok(canon) => Some(canon),
195                 Err(e) => panic!("failed to get realpath: {}", e),
196             })
197     }
198
199     match canonicalize(os::self_exe_name()) {
200         Some(mut p) => { p.pop(); p.pop(); p }
201         None => panic!("can't determine value for sysroot")
202     }
203 }
204
205 #[cfg(windows)]
206 static PATH_ENTRY_SEPARATOR: &'static str = ";";
207 #[cfg(not(windows))]
208 static PATH_ENTRY_SEPARATOR: &'static str = ":";
209
210 /// Returns RUST_PATH as a string, without default paths added
211 pub fn get_rust_path() -> Option<String> {
212     os::getenv("RUST_PATH").map(|x| x.to_string())
213 }
214
215 /// Returns the value of RUST_PATH, as a list
216 /// of Paths. Includes default entries for, if they exist:
217 /// $HOME/.rust
218 /// DIR/.rust for any DIR that's the current working directory
219 /// or an ancestor of it
220 pub fn rust_path() -> Vec<Path> {
221     let mut env_rust_path: Vec<Path> = match get_rust_path() {
222         Some(env_path) => {
223             let env_path_components =
224                 env_path.split_str(PATH_ENTRY_SEPARATOR);
225             env_path_components.map(|s| Path::new(s)).collect()
226         }
227         None => Vec::new()
228     };
229     let mut cwd = os::getcwd().unwrap();
230     // now add in default entries
231     let cwd_dot_rust = cwd.join(".rust");
232     if !env_rust_path.contains(&cwd_dot_rust) {
233         env_rust_path.push(cwd_dot_rust);
234     }
235     if !env_rust_path.contains(&cwd) {
236         env_rust_path.push(cwd.clone());
237     }
238     loop {
239         if { let f = cwd.filename(); f.is_none() || f.unwrap() == b".." } {
240             break
241         }
242         cwd.set_filename(".rust");
243         if !env_rust_path.contains(&cwd) && cwd.exists() {
244             env_rust_path.push(cwd.clone());
245         }
246         cwd.pop();
247     }
248     let h = os::homedir();
249     for h in h.iter() {
250         let p = h.join(".rust");
251         if !env_rust_path.contains(&p) && p.exists() {
252             env_rust_path.push(p);
253         }
254     }
255     env_rust_path
256 }
257
258 // The name of the directory rustc expects libraries to be located.
259 // On Unix should be "lib", on windows "bin"
260 #[cfg(unix)]
261 fn find_libdir(sysroot: &Path) -> String {
262     // FIXME: This is a quick hack to make the rustc binary able to locate
263     // Rust libraries in Linux environments where libraries might be installed
264     // to lib64/lib32. This would be more foolproof by basing the sysroot off
265     // of the directory where librustc is located, rather than where the rustc
266     // binary is.
267     //If --libdir is set during configuration to the value other than
268     // "lib" (i.e. non-default), this value is used (see issue #16552).
269
270     match option_env!("CFG_LIBDIR_RELATIVE") {
271         Some(libdir) if libdir != "lib" => return libdir.to_string(),
272         _ => if sysroot.join(primary_libdir_name()).join(rustlibdir()).exists() {
273             return primary_libdir_name();
274         } else {
275             return secondary_libdir_name();
276         }
277     }
278
279     #[cfg(target_word_size = "64")]
280     fn primary_libdir_name() -> String {
281         "lib64".to_string()
282     }
283
284     #[cfg(target_word_size = "32")]
285     fn primary_libdir_name() -> String {
286         "lib32".to_string()
287     }
288
289     fn secondary_libdir_name() -> String {
290         "lib".to_string()
291     }
292 }
293
294 #[cfg(windows)]
295 fn find_libdir(_sysroot: &Path) -> String {
296     "bin".to_string()
297 }
298
299 // The name of rustc's own place to organize libraries.
300 // Used to be "rustc", now the default is "rustlib"
301 pub fn rustlibdir() -> String {
302     "rustlib".to_string()
303 }