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