]> git.lizzy.rs Git - rust.git/blob - src/librustc_codegen_ssa/back/rpath.rs
Suggest defining type parameter when appropriate
[rust.git] / src / librustc_codegen_ssa / back / rpath.rs
1 use rustc_data_structures::fx::FxHashSet;
2 use std::env;
3 use std::fs;
4 use std::path::{Path, PathBuf};
5
6 use rustc::middle::cstore::LibSource;
7 use rustc_hir::def_id::CrateNum;
8
9 pub struct RPathConfig<'a> {
10     pub used_crates: &'a [(CrateNum, LibSource)],
11     pub out_filename: PathBuf,
12     pub is_like_osx: bool,
13     pub has_rpath: bool,
14     pub linker_is_gnu: bool,
15     pub get_install_prefix_lib_path: &'a mut dyn FnMut() -> PathBuf,
16 }
17
18 pub fn get_rpath_flags(config: &mut RPathConfig<'_>) -> Vec<String> {
19     // No rpath on windows
20     if !config.has_rpath {
21         return Vec::new();
22     }
23
24     debug!("preparing the RPATH!");
25
26     let libs = config.used_crates.clone();
27     let libs = libs.iter().filter_map(|&(_, ref l)| l.option()).collect::<Vec<_>>();
28     let rpaths = get_rpaths(config, &libs);
29     let mut flags = rpaths_to_flags(&rpaths);
30
31     // Use DT_RUNPATH instead of DT_RPATH if available
32     if config.linker_is_gnu {
33         flags.push("-Wl,--enable-new-dtags".to_owned());
34     }
35
36     flags
37 }
38
39 fn rpaths_to_flags(rpaths: &[String]) -> Vec<String> {
40     let mut ret = Vec::with_capacity(rpaths.len()); // the minimum needed capacity
41
42     for rpath in rpaths {
43         if rpath.contains(',') {
44             ret.push("-Wl,-rpath".into());
45             ret.push("-Xlinker".into());
46             ret.push(rpath.clone());
47         } else {
48             ret.push(format!("-Wl,-rpath,{}", &(*rpath)));
49         }
50     }
51
52     ret
53 }
54
55 fn get_rpaths(config: &mut RPathConfig<'_>, libs: &[PathBuf]) -> Vec<String> {
56     debug!("output: {:?}", config.out_filename.display());
57     debug!("libs:");
58     for libpath in libs {
59         debug!("    {:?}", libpath.display());
60     }
61
62     // Use relative paths to the libraries. Binaries can be moved
63     // as long as they maintain the relative relationship to the
64     // crates they depend on.
65     let rel_rpaths = get_rpaths_relative_to_output(config, libs);
66
67     // And a final backup rpath to the global library location.
68     let fallback_rpaths = vec![get_install_prefix_rpath(config)];
69
70     fn log_rpaths(desc: &str, rpaths: &[String]) {
71         debug!("{} rpaths:", desc);
72         for rpath in rpaths {
73             debug!("    {}", *rpath);
74         }
75     }
76
77     log_rpaths("relative", &rel_rpaths);
78     log_rpaths("fallback", &fallback_rpaths);
79
80     let mut rpaths = rel_rpaths;
81     rpaths.extend_from_slice(&fallback_rpaths);
82
83     // Remove duplicates
84     let rpaths = minimize_rpaths(&rpaths);
85
86     rpaths
87 }
88
89 fn get_rpaths_relative_to_output(config: &mut RPathConfig<'_>, libs: &[PathBuf]) -> Vec<String> {
90     libs.iter().map(|a| get_rpath_relative_to_output(config, a)).collect()
91 }
92
93 fn get_rpath_relative_to_output(config: &mut RPathConfig<'_>, lib: &Path) -> String {
94     // Mac doesn't appear to support $ORIGIN
95     let prefix = if config.is_like_osx { "@loader_path" } else { "$ORIGIN" };
96
97     let cwd = env::current_dir().unwrap();
98     let mut lib = fs::canonicalize(&cwd.join(lib)).unwrap_or_else(|_| cwd.join(lib));
99     lib.pop(); // strip filename
100     let mut output = cwd.join(&config.out_filename);
101     output.pop(); // strip filename
102     let output = fs::canonicalize(&output).unwrap_or(output);
103     let relative = path_relative_from(&lib, &output)
104         .unwrap_or_else(|| panic!("couldn't create relative path from {:?} to {:?}", output, lib));
105     // FIXME (#9639): This needs to handle non-utf8 paths
106     format!("{}/{}", prefix, 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         path.is_absolute().then(|| PathBuf::from(path))
118     } else {
119         let mut ita = path.components();
120         let mut itb = base.components();
121         let mut comps: Vec<Component<'_>> = vec![];
122         loop {
123             match (ita.next(), itb.next()) {
124                 (None, None) => break,
125                 (Some(a), None) => {
126                     comps.push(a);
127                     comps.extend(ita.by_ref());
128                     break;
129                 }
130                 (None, _) => comps.push(Component::ParentDir),
131                 (Some(a), Some(b)) if comps.is_empty() && a == b => (),
132                 (Some(a), Some(b)) if b == Component::CurDir => comps.push(a),
133                 (Some(_), Some(b)) if b == Component::ParentDir => return None,
134                 (Some(a), Some(_)) => {
135                     comps.push(Component::ParentDir);
136                     comps.extend(itb.map(|_| Component::ParentDir));
137                     comps.push(a);
138                     comps.extend(ita.by_ref());
139                     break;
140                 }
141             }
142         }
143         Some(comps.iter().map(|c| c.as_os_str()).collect())
144     }
145 }
146
147 fn get_install_prefix_rpath(config: &mut RPathConfig<'_>) -> String {
148     let path = (config.get_install_prefix_lib_path)();
149     let path = env::current_dir().unwrap().join(&path);
150     // FIXME (#9639): This needs to handle non-utf8 paths
151     path.to_str().expect("non-utf8 component in rpath").to_owned()
152 }
153
154 fn minimize_rpaths(rpaths: &[String]) -> Vec<String> {
155     let mut set = FxHashSet::default();
156     let mut minimized = Vec::new();
157     for rpath in rpaths {
158         if set.insert(rpath) {
159             minimized.push(rpath.clone());
160         }
161     }
162     minimized
163 }
164
165 #[cfg(all(unix, test))]
166 mod tests;