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