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