]> git.lizzy.rs Git - rust.git/blob - src/librustc_back/rpath.rs
Auto merge of #31915 - nagisa:mir-unpretty-fix, r=arielb1
[rust.git] / src / librustc_back / rpath.rs
1 // Copyright 2012-2015 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 use std::collections::HashSet;
12 use std::env;
13 use std::path::{Path, PathBuf};
14 use std::fs;
15 use syntax::ast;
16
17 pub struct RPathConfig<'a> {
18     pub used_crates: Vec<(ast::CrateNum, Option<PathBuf>)>,
19     pub out_filename: PathBuf,
20     pub is_like_osx: bool,
21     pub has_rpath: bool,
22     pub linker_is_gnu: bool,
23     pub get_install_prefix_lib_path: &'a mut FnMut() -> PathBuf,
24 }
25
26 pub fn get_rpath_flags(config: &mut RPathConfig) -> Vec<String> {
27     // No rpath on windows
28     if !config.has_rpath {
29         return Vec::new();
30     }
31
32     let mut flags = Vec::new();
33
34     debug!("preparing the RPATH!");
35
36     let libs = config.used_crates.clone();
37     let libs = libs.into_iter().filter_map(|(_, l)| l).collect::<Vec<_>>();
38     let rpaths = get_rpaths(config, &libs[..]);
39     flags.extend_from_slice(&rpaths_to_flags(&rpaths[..]));
40
41     // Use DT_RUNPATH instead of DT_RPATH if available
42     if config.linker_is_gnu {
43         flags.push("-Wl,--enable-new-dtags".to_string());
44     }
45
46     flags
47 }
48
49 fn rpaths_to_flags(rpaths: &[String]) -> Vec<String> {
50     let mut ret = Vec::new();
51     for rpath in rpaths {
52         ret.push(format!("-Wl,-rpath,{}", &(*rpath)));
53     }
54     return ret;
55 }
56
57 fn get_rpaths(config: &mut RPathConfig, libs: &[PathBuf]) -> Vec<String> {
58     debug!("output: {:?}", config.out_filename.display());
59     debug!("libs:");
60     for libpath in libs {
61         debug!("    {:?}", libpath.display());
62     }
63
64     // Use relative paths to the libraries. Binaries can be moved
65     // as long as they maintain the relative relationship to the
66     // crates they depend on.
67     let rel_rpaths = get_rpaths_relative_to_output(config, libs);
68
69     // And a final backup rpath to the global library location.
70     let fallback_rpaths = vec!(get_install_prefix_rpath(config));
71
72     fn log_rpaths(desc: &str, rpaths: &[String]) {
73         debug!("{} rpaths:", desc);
74         for rpath in rpaths {
75             debug!("    {}", *rpath);
76         }
77     }
78
79     log_rpaths("relative", &rel_rpaths[..]);
80     log_rpaths("fallback", &fallback_rpaths[..]);
81
82     let mut rpaths = rel_rpaths;
83     rpaths.extend_from_slice(&fallback_rpaths[..]);
84
85     // Remove duplicates
86     let rpaths = minimize_rpaths(&rpaths[..]);
87     return rpaths;
88 }
89
90 fn get_rpaths_relative_to_output(config: &mut RPathConfig,
91                                  libs: &[PathBuf]) -> Vec<String> {
92     libs.iter().map(|a| get_rpath_relative_to_output(config, a)).collect()
93 }
94
95 fn get_rpath_relative_to_output(config: &mut RPathConfig, lib: &Path) -> String {
96     // Mac doesn't appear to support $ORIGIN
97     let prefix = if config.is_like_osx {
98         "@loader_path"
99     } else {
100         "$ORIGIN"
101     };
102
103     let cwd = env::current_dir().unwrap();
104     let mut lib = fs::canonicalize(&cwd.join(lib)).unwrap_or(cwd.join(lib));
105     lib.pop();
106     let mut output = cwd.join(&config.out_filename);
107     output.pop();
108     let output = fs::canonicalize(&output).unwrap_or(output);
109     let relative = path_relative_from(&lib, &output)
110         .expect(&format!("couldn't create relative path from {:?} to {:?}", output, lib));
111     // FIXME (#9639): This needs to handle non-utf8 paths
112     format!("{}/{}", prefix,
113             relative.to_str().expect("non-utf8 component in path"))
114 }
115
116 // This routine is adapted from the *old* Path's `path_relative_from`
117 // function, which works differently from the new `relative_from` function.
118 // In particular, this handles the case on unix where both paths are
119 // absolute but with only the root as the common directory.
120 fn path_relative_from(path: &Path, base: &Path) -> Option<PathBuf> {
121     use std::path::Component;
122
123     if path.is_absolute() != base.is_absolute() {
124         if path.is_absolute() {
125             Some(PathBuf::from(path))
126         } else {
127             None
128         }
129     } else {
130         let mut ita = path.components();
131         let mut itb = base.components();
132         let mut comps: Vec<Component> = vec![];
133         loop {
134             match (ita.next(), itb.next()) {
135                 (None, None) => break,
136                 (Some(a), None) => {
137                     comps.push(a);
138                     comps.extend(ita.by_ref());
139                     break;
140                 }
141                 (None, _) => comps.push(Component::ParentDir),
142                 (Some(a), Some(b)) if comps.is_empty() && a == b => (),
143                 (Some(a), Some(b)) if b == Component::CurDir => comps.push(a),
144                 (Some(_), Some(b)) if b == Component::ParentDir => return None,
145                 (Some(a), Some(_)) => {
146                     comps.push(Component::ParentDir);
147                     for _ in itb {
148                         comps.push(Component::ParentDir);
149                     }
150                     comps.push(a);
151                     comps.extend(ita.by_ref());
152                     break;
153                 }
154             }
155         }
156         Some(comps.iter().map(|c| c.as_os_str()).collect())
157     }
158 }
159
160
161 fn get_install_prefix_rpath(config: &mut RPathConfig) -> String {
162     let path = (config.get_install_prefix_lib_path)();
163     let path = env::current_dir().unwrap().join(&path);
164     // FIXME (#9639): This needs to handle non-utf8 paths
165     path.to_str().expect("non-utf8 component in rpath").to_string()
166 }
167
168 fn minimize_rpaths(rpaths: &[String]) -> Vec<String> {
169     let mut set = HashSet::new();
170     let mut minimized = Vec::new();
171     for rpath in rpaths {
172         if set.insert(&rpath[..]) {
173             minimized.push(rpath.clone());
174         }
175     }
176     minimized
177 }
178
179 #[cfg(all(unix, test))]
180 mod tests {
181     use super::{RPathConfig};
182     use super::{minimize_rpaths, rpaths_to_flags, get_rpath_relative_to_output};
183     use std::path::{Path, PathBuf};
184
185     #[test]
186     fn test_rpaths_to_flags() {
187         let flags = rpaths_to_flags(&[
188             "path1".to_string(),
189             "path2".to_string()
190         ]);
191         assert_eq!(flags,
192                    ["-Wl,-rpath,path1",
193                     "-Wl,-rpath,path2"]);
194     }
195
196     #[test]
197     fn test_minimize1() {
198         let res = minimize_rpaths(&[
199             "rpath1".to_string(),
200             "rpath2".to_string(),
201             "rpath1".to_string()
202         ]);
203         assert!(res == [
204             "rpath1",
205             "rpath2",
206         ]);
207     }
208
209     #[test]
210     fn test_minimize2() {
211         let res = minimize_rpaths(&[
212             "1a".to_string(),
213             "2".to_string(),
214             "2".to_string(),
215             "1a".to_string(),
216             "4a".to_string(),
217             "1a".to_string(),
218             "2".to_string(),
219             "3".to_string(),
220             "4a".to_string(),
221             "3".to_string()
222         ]);
223         assert!(res == [
224             "1a",
225             "2",
226             "4a",
227             "3",
228         ]);
229     }
230
231     #[test]
232     fn test_rpath_relative() {
233         if cfg!(target_os = "macos") {
234             let config = &mut RPathConfig {
235                 used_crates: Vec::new(),
236                 has_rpath: true,
237                 is_like_osx: true,
238                 linker_is_gnu: false,
239                 out_filename: PathBuf::from("bin/rustc"),
240                 get_install_prefix_lib_path: &mut || panic!(),
241             };
242             let res = get_rpath_relative_to_output(config,
243                                                    Path::new("lib/libstd.so"));
244             assert_eq!(res, "@loader_path/../lib");
245         } else {
246             let config = &mut RPathConfig {
247                 used_crates: Vec::new(),
248                 out_filename: PathBuf::from("bin/rustc"),
249                 get_install_prefix_lib_path: &mut || panic!(),
250                 has_rpath: true,
251                 is_like_osx: false,
252                 linker_is_gnu: true,
253             };
254             let res = get_rpath_relative_to_output(config,
255                                                    Path::new("lib/libstd.so"));
256             assert_eq!(res, "$ORIGIN/../lib");
257         }
258     }
259 }