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