1use std::path::{Component, Path, PathBuf};
8
9use kh_runtime::translate_path_with_root;
10
11#[derive(Debug, Clone, Copy)]
13pub struct ResolveContext<'a> {
14 pub bottle_root: Option<&'a Path>,
16 pub executable_dir: &'a Path,
18 pub loader_dir: &'a Path,
20 pub rpaths: &'a [String],
22}
23
24#[derive(Debug, Clone, PartialEq, Eq)]
26pub enum ResolveError {
27 Empty,
29 Escape(String),
31 NestedRpath,
33 NoBottle,
35 OutsideAllowlist(PathBuf),
37 InvalidEncoding,
39}
40
41impl std::fmt::Display for ResolveError {
42 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
43 match self {
44 Self::Empty => write!(f, "empty install name"),
45 Self::Escape(p) => write!(f, "path escape: {p}"),
46 Self::NestedRpath => write!(f, "nested @rpath in LC_RPATH"),
47 Self::NoBottle => write!(f, "absolute install name requires bottle root"),
48 Self::OutsideAllowlist(p) => {
49 write!(f, "path outside map allowlist: {}", p.display())
50 }
51 Self::InvalidEncoding => write!(f, "invalid path encoding"),
52 }
53 }
54}
55
56impl std::error::Error for ResolveError {}
57
58pub fn resolve_install_name(
63 install_name: &str,
64 ctx: &ResolveContext<'_>,
65) -> Result<PathBuf, ResolveError> {
66 if install_name.is_empty() {
67 return Err(ResolveError::Empty);
68 }
69
70 let host = if let Some(rest) = install_name.strip_prefix("@executable_path/") {
71 join_no_dotdot(ctx.executable_dir, rest)?
72 } else if install_name == "@executable_path" {
73 ctx.executable_dir.to_path_buf()
74 } else if let Some(rest) = install_name.strip_prefix("@loader_path/") {
75 join_no_dotdot(ctx.loader_dir, rest)?
76 } else if install_name == "@loader_path" {
77 ctx.loader_dir.to_path_buf()
78 } else if let Some(rest) = install_name.strip_prefix("@rpath/") {
79 resolve_rpath(rest, ctx)?
80 } else if install_name == "@rpath" {
81 return Err(ResolveError::Empty);
82 } else if install_name.starts_with('@') {
83 return Err(ResolveError::Escape(install_name.to_owned()));
85 } else if is_absolute_install_name(install_name) {
86 resolve_absolute(install_name, ctx)?
87 } else {
88 join_no_dotdot(ctx.loader_dir, install_name)?
90 };
91
92 ensure_allowlisted(&host, ctx)?;
93 Ok(host)
94}
95
96fn is_absolute_install_name(name: &str) -> bool {
97 name.starts_with('/')
98}
99
100fn resolve_absolute(install_name: &str, ctx: &ResolveContext<'_>) -> Result<PathBuf, ResolveError> {
101 let Some(root) = ctx.bottle_root else {
102 return Err(ResolveError::NoBottle);
104 };
105 translate_path_with_root(Some(root), install_name).map_err(path_err_to_resolve)
106}
107
108fn resolve_rpath(rest: &str, ctx: &ResolveContext<'_>) -> Result<PathBuf, ResolveError> {
109 if rest.is_empty() {
110 return Err(ResolveError::Empty);
111 }
112
113 let mut last_allowlisted: Option<PathBuf> = None;
114
115 for rpath in ctx.rpaths {
116 if rpath.contains("@rpath") {
117 return Err(ResolveError::NestedRpath);
118 }
119 let base = expand_rpath_value(rpath, ctx)?;
120 let candidate = join_no_dotdot(&base, rest)?;
121 match ensure_allowlisted(&candidate, ctx) {
122 Ok(()) => {
123 if candidate.exists() {
124 return Ok(candidate);
125 }
126 last_allowlisted = Some(candidate);
127 }
128 Err(ResolveError::OutsideAllowlist(_)) => {}
129 Err(err) => return Err(err),
130 }
131 }
132
133 last_allowlisted.ok_or_else(|| ResolveError::OutsideAllowlist(PathBuf::from(rest)))
134}
135
136fn expand_rpath_value(rpath: &str, ctx: &ResolveContext<'_>) -> Result<PathBuf, ResolveError> {
137 if rpath.is_empty() {
138 return Err(ResolveError::Empty);
139 }
140 if let Some(rest) = rpath.strip_prefix("@executable_path/") {
141 join_no_dotdot(ctx.executable_dir, rest)
142 } else if rpath == "@executable_path" {
143 Ok(ctx.executable_dir.to_path_buf())
144 } else if let Some(rest) = rpath.strip_prefix("@loader_path/") {
145 join_no_dotdot(ctx.loader_dir, rest)
146 } else if rpath == "@loader_path" {
147 Ok(ctx.loader_dir.to_path_buf())
148 } else if rpath.starts_with('@') {
149 Err(ResolveError::Escape(rpath.to_owned()))
150 } else if is_absolute_install_name(rpath) {
151 resolve_absolute(rpath, ctx)
152 } else {
153 join_no_dotdot(ctx.loader_dir, rpath)
155 }
156}
157
158fn join_no_dotdot(base: &Path, rest: &str) -> Result<PathBuf, ResolveError> {
159 if rest.is_empty() {
160 return Ok(base.to_path_buf());
161 }
162 let mut out = base.to_path_buf();
163 for comp in Path::new(rest).components() {
164 match comp {
165 Component::Normal(s) => out.push(s),
166 Component::CurDir => {}
167 Component::ParentDir | Component::Prefix(_) | Component::RootDir => {
168 return Err(ResolveError::Escape(rest.to_owned()));
169 }
170 }
171 }
172 Ok(out)
173}
174
175fn ensure_allowlisted(host: &Path, ctx: &ResolveContext<'_>) -> Result<(), ResolveError> {
180 let check = path_for_allowlist_check(host);
181
182 if let Some(root) = ctx.bottle_root {
183 let root_canon = canonicalize_or_owned(root);
184 if is_path_under(&check, &root_canon) {
185 return Ok(());
186 }
187 }
188
189 let exe_canon = canonicalize_or_owned(ctx.executable_dir);
190 if is_path_under(&check, &exe_canon) {
191 return Ok(());
192 }
193
194 Err(ResolveError::OutsideAllowlist(host.to_path_buf()))
195}
196
197fn path_for_allowlist_check(host: &Path) -> PathBuf {
198 if host.exists() {
199 return host
200 .canonicalize()
201 .unwrap_or_else(|_| lexical_normalize(host));
202 }
203 canonicalize_with_missing_tail(host)
205}
206
207fn canonicalize_with_missing_tail(host: &Path) -> PathBuf {
208 let mut components: Vec<_> = host.components().collect();
209 let mut tail = Vec::new();
210 while !components.is_empty() {
211 let prefix: PathBuf = components.iter().collect();
212 if prefix.exists() {
213 let mut base = prefix.canonicalize().unwrap_or(prefix);
214 for c in tail.into_iter().rev() {
215 base.push(c);
216 }
217 return base;
218 }
219 if let Some(Component::Normal(s)) = components.pop() {
220 tail.push(s.to_os_string());
221 } else {
222 break;
223 }
224 }
225 lexical_normalize(host)
226}
227
228fn canonicalize_or_owned(path: &Path) -> PathBuf {
229 path.canonicalize().unwrap_or_else(|_| path.to_path_buf())
230}
231
232fn lexical_normalize(path: &Path) -> PathBuf {
233 let mut out = PathBuf::new();
234 for comp in path.components() {
235 match comp {
236 Component::ParentDir => {
237 let _ = out.pop();
238 }
239 Component::CurDir => {}
240 other => out.push(other.as_os_str()),
241 }
242 }
243 out
244}
245
246fn is_path_under(path: &Path, base: &Path) -> bool {
247 path.starts_with(base)
248}
249
250fn path_err_to_resolve(err: kh_runtime::PathError) -> ResolveError {
251 match err {
252 kh_runtime::PathError::Empty => ResolveError::Empty,
253 kh_runtime::PathError::Escape(s) => ResolveError::Escape(s),
254 kh_runtime::PathError::InvalidEncoding => ResolveError::InvalidEncoding,
255 }
256}
257
258#[cfg(test)]
259#[allow(clippy::expect_used, clippy::unwrap_used)]
260mod tests {
261 use super::*;
262 use std::fs::{self, File};
263 use std::io::Write;
264
265 fn ctx<'a>(
266 bottle: Option<&'a Path>,
267 exe_dir: &'a Path,
268 loader_dir: &'a Path,
269 rpaths: &'a [String],
270 ) -> ResolveContext<'a> {
271 ResolveContext {
272 bottle_root: bottle,
273 executable_dir: exe_dir,
274 loader_dir,
275 rpaths,
276 }
277 }
278
279 #[test]
280 fn absolute_without_bottle_is_no_bottle() {
281 let exe = Path::new("/tmp/kh-exe-dir");
282 let c = ctx(None, exe, exe, &[]);
283 let err = resolve_install_name("/usr/lib/libSystem.B.dylib", &c).unwrap_err();
284 assert_eq!(err, ResolveError::NoBottle);
285 }
286
287 #[test]
288 fn absolute_with_bottle_under_root() {
289 let root = std::env::temp_dir().join(format!("kh-resolve-bottle-{}", std::process::id()));
290 let lib_dir = root.join("usr/lib");
291 fs::create_dir_all(&lib_dir).unwrap();
292 let lib = lib_dir.join("libFoo.dylib");
293 File::create(&lib).unwrap().write_all(b"x").unwrap();
294
295 let exe = root.join("bin");
296 fs::create_dir_all(&exe).unwrap();
297
298 let c = ctx(Some(root.as_path()), &exe, &exe, &[]);
299 let host = resolve_install_name("/usr/lib/libFoo.dylib", &c).unwrap();
300 assert_eq!(host, lib);
301 drop(fs::remove_dir_all(root));
302 }
303
304 #[test]
305 fn executable_path_relative() {
306 let dir = std::env::temp_dir().join(format!("kh-resolve-exe-{}", std::process::id()));
307 fs::create_dir_all(&dir).unwrap();
308 let dylib = dir.join("libkh_add.dylib");
309 File::create(&dylib).unwrap().write_all(b"x").unwrap();
310
311 let c = ctx(None, &dir, &dir, &[]);
312 let host = resolve_install_name("@executable_path/libkh_add.dylib", &c).unwrap();
313 assert_eq!(host, dylib);
314 drop(fs::remove_dir_all(dir));
315 }
316
317 #[test]
318 fn loader_path_relative() {
319 let exe_dir =
321 std::env::temp_dir().join(format!("kh-resolve-loader-{}", std::process::id()));
322 let loader = exe_dir.join("Frameworks");
323 fs::create_dir_all(&loader).unwrap();
324 let dylib = loader.join("Inner.dylib");
325 File::create(&dylib).unwrap().write_all(b"x").unwrap();
326
327 let c = ctx(None, &exe_dir, &loader, &[]);
328 let host = resolve_install_name("@loader_path/Inner.dylib", &c).unwrap();
329 assert_eq!(host, dylib);
330 drop(fs::remove_dir_all(exe_dir));
331 }
332
333 #[test]
334 fn rpath_first_hit() {
335 let dir = std::env::temp_dir().join(format!("kh-resolve-rpath-{}", std::process::id()));
336 let a = dir.join("a");
337 let b = dir.join("b");
338 fs::create_dir_all(&a).unwrap();
339 fs::create_dir_all(&b).unwrap();
340 let target = b.join("libX.dylib");
342 File::create(&target).unwrap().write_all(b"x").unwrap();
343
344 let rpaths = vec![
345 "@executable_path/a".to_owned(),
346 "@executable_path/b".to_owned(),
347 ];
348 let c = ctx(None, &dir, &dir, &rpaths);
349 let host = resolve_install_name("@rpath/libX.dylib", &c).unwrap();
350 assert_eq!(host, target);
351 drop(fs::remove_dir_all(dir));
352 }
353
354 #[test]
355 fn rejects_dotdot() {
356 let exe = Path::new("/tmp/kh-exe");
357 let c = ctx(None, exe, exe, &[]);
358 let err = resolve_install_name("@executable_path/../etc/passwd", &c).unwrap_err();
359 assert!(matches!(err, ResolveError::Escape(_)));
360 }
361
362 #[test]
363 fn bottle_symlink_escape_rejected() {
364 let root = std::env::temp_dir().join(format!("kh-resolve-symlink-{}", std::process::id()));
365 let outside =
366 std::env::temp_dir().join(format!("kh-resolve-outside-{}", std::process::id()));
367 fs::create_dir_all(&root).unwrap();
368 fs::create_dir_all(&outside).unwrap();
369 let outside_lib = outside.join("evil.dylib");
370 File::create(&outside_lib).unwrap().write_all(b"x").unwrap();
371
372 let link = root.join("escape.dylib");
373 #[cfg(unix)]
374 std::os::unix::fs::symlink(&outside_lib, &link).unwrap();
375
376 let exe = root.join("bin");
377 fs::create_dir_all(&exe).unwrap();
378
379 let c = ctx(Some(root.as_path()), &exe, &exe, &[]);
380 let result = resolve_install_name("/escape.dylib", &c);
383 assert!(
384 matches!(result, Err(ResolveError::OutsideAllowlist(_))),
385 "expected OutsideAllowlist, got {result:?}"
386 );
387
388 drop(fs::remove_dir_all(root));
389 drop(fs::remove_dir_all(outside));
390 }
391
392 #[test]
393 fn absolute_planted_host_path_still_no_bottle() {
394 let planted =
397 std::env::temp_dir().join(format!("kh-fake-libsystem-{}", std::process::id()));
398 File::create(&planted).unwrap().write_all(b"x").unwrap();
399 let abs = planted.to_str().expect("utf8 temp path");
400 let exe = Path::new("/tmp/kh-exe-dir");
401 let c = ctx(None, exe, exe, &[]);
402 let err = resolve_install_name(abs, &c).unwrap_err();
403 assert_eq!(err, ResolveError::NoBottle);
404 drop(fs::remove_file(planted));
405 }
406}