]> git.lizzy.rs Git - rust.git/blob - src/librustc_codegen_ssa/back/rpath.rs
Add note to src/ci/docker/README.md about multiple docker images
[rust.git] / src / librustc_codegen_ssa / back / rpath.rs
1 use rustc_data_structures::fx::FxHashSet;
2 use std::env;
3 use std::path::{Path, PathBuf};
4 use std::fs;
5
6 use rustc::hir::def_id::CrateNum;
7 use rustc::middle::cstore::LibSource;
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<'_>,
90                                  libs: &[PathBuf]) -> Vec<String> {
91     libs.iter().map(|a| get_rpath_relative_to_output(config, a)).collect()
92 }
93
94 fn get_rpath_relative_to_output(config: &mut RPathConfig<'_>, lib: &Path) -> String {
95     // Mac doesn't appear to support $ORIGIN
96     let prefix = if config.is_like_osx {
97         "@loader_path"
98     } else {
99         "$ORIGIN"
100     };
101
102     let cwd = env::current_dir().unwrap();
103     let mut lib = fs::canonicalize(&cwd.join(lib)).unwrap_or_else(|_| cwd.join(lib));
104     lib.pop(); // strip filename
105     let mut output = cwd.join(&config.out_filename);
106     output.pop(); // strip filename
107     let output = fs::canonicalize(&output).unwrap_or(output);
108     let relative = path_relative_from(&lib, &output).unwrap_or_else(||
109         panic!("couldn't create relative path from {:?} to {:?}", output, lib));
110     // FIXME (#9639): This needs to handle non-utf8 paths
111     format!("{}/{}", prefix, relative.to_str().expect("non-utf8 component in path"))
112 }
113
114 // This routine is adapted from the *old* Path's `path_relative_from`
115 // function, which works differently from the new `relative_from` function.
116 // In particular, this handles the case on unix where both paths are
117 // absolute but with only the root as the common directory.
118 fn path_relative_from(path: &Path, base: &Path) -> Option<PathBuf> {
119     use std::path::Component;
120
121     if path.is_absolute() != base.is_absolute() {
122         if path.is_absolute() {
123             Some(PathBuf::from(path))
124         } else {
125             None
126         }
127     } else {
128         let mut ita = path.components();
129         let mut itb = base.components();
130         let mut comps: Vec<Component<'_>> = vec![];
131         loop {
132             match (ita.next(), itb.next()) {
133                 (None, None) => break,
134                 (Some(a), None) => {
135                     comps.push(a);
136                     comps.extend(ita.by_ref());
137                     break;
138                 }
139                 (None, _) => comps.push(Component::ParentDir),
140                 (Some(a), Some(b)) if comps.is_empty() && a == b => (),
141                 (Some(a), Some(b)) if b == Component::CurDir => comps.push(a),
142                 (Some(_), Some(b)) if b == Component::ParentDir => return None,
143                 (Some(a), Some(_)) => {
144                     comps.push(Component::ParentDir);
145                     comps.extend(itb.map(|_| Component::ParentDir));
146                     comps.push(a);
147                     comps.extend(ita.by_ref());
148                     break;
149                 }
150             }
151         }
152         Some(comps.iter().map(|c| c.as_os_str()).collect())
153     }
154 }
155
156
157 fn get_install_prefix_rpath(config: &mut RPathConfig<'_>) -> String {
158     let path = (config.get_install_prefix_lib_path)();
159     let path = env::current_dir().unwrap().join(&path);
160     // FIXME (#9639): This needs to handle non-utf8 paths
161     path.to_str().expect("non-utf8 component in rpath").to_owned()
162 }
163
164 fn minimize_rpaths(rpaths: &[String]) -> Vec<String> {
165     let mut set = FxHashSet::default();
166     let mut minimized = Vec::new();
167     for rpath in rpaths {
168         if set.insert(rpath) {
169             minimized.push(rpath.clone());
170         }
171     }
172     minimized
173 }
174
175 #[cfg(all(unix, test))]
176 mod tests;