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