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_allow_dotdot(ctx.executable_dir, rest)?
74 } else if install_name == "@executable_path" {
75 ctx.executable_dir.to_path_buf()
76 } else if let Some(rest) = install_name.strip_prefix("@loader_path/") {
77 join_allow_dotdot(ctx.loader_dir, rest)?
78 } else if install_name == "@loader_path" {
79 ctx.loader_dir.to_path_buf()
80 } else if let Some(rest) = install_name.strip_prefix("@rpath/") {
81 resolve_rpath(rest, ctx)?
82 } else if install_name == "@rpath" {
83 return Err(ResolveError::Empty);
84 } else if install_name.starts_with('@') {
85 return Err(ResolveError::Escape(install_name.to_owned()));
87 } else if is_absolute_install_name(install_name) {
88 resolve_absolute(install_name, ctx)?
89 } else {
90 join_no_dotdot(ctx.loader_dir, install_name)?
92 };
93
94 ensure_allowlisted(&host, ctx)?;
95 Ok(host)
96}
97
98fn is_absolute_install_name(name: &str) -> bool {
99 name.starts_with('/')
100}
101
102fn resolve_absolute(install_name: &str, ctx: &ResolveContext<'_>) -> Result<PathBuf, ResolveError> {
103 let Some(root) = ctx.bottle_root else {
104 return Err(ResolveError::NoBottle);
106 };
107 translate_path_with_root(Some(root), install_name).map_err(path_err_to_resolve)
108}
109
110fn resolve_rpath(rest: &str, ctx: &ResolveContext<'_>) -> Result<PathBuf, ResolveError> {
111 if rest.is_empty() {
112 return Err(ResolveError::Empty);
113 }
114
115 let mut last_allowlisted: Option<PathBuf> = None;
116
117 if let Ok(dyld) = std::env::var("DYLD_LIBRARY_PATH") {
121 for dir in dyld.split(':').filter(|d| !d.is_empty()) {
122 match candidate_from_dyld_dir(dir, rest, ctx) {
123 Ok(candidate) => {
124 if candidate.exists() {
125 return Ok(candidate);
126 }
127 last_allowlisted = Some(candidate);
128 }
129 Err(
130 ResolveError::OutsideAllowlist(_)
131 | ResolveError::NoBottle
132 | ResolveError::Escape(_),
133 ) => {}
134 Err(err) => return Err(err),
135 }
136 }
137 }
138
139 for rpath in ctx.rpaths {
140 if rpath.contains("@rpath") {
141 return Err(ResolveError::NestedRpath);
142 }
143 let base = expand_rpath_value(rpath, ctx)?;
144 let candidate = join_no_dotdot(&base, rest)?;
146 match ensure_allowlisted(&candidate, ctx) {
147 Ok(()) => {
148 if candidate.exists() {
149 return Ok(candidate);
150 }
151 last_allowlisted = Some(candidate);
152 }
153 Err(ResolveError::OutsideAllowlist(_)) => {}
154 Err(err) => return Err(err),
155 }
156 }
157
158 last_allowlisted.ok_or_else(|| ResolveError::OutsideAllowlist(PathBuf::from(rest)))
159}
160
161fn candidate_from_dyld_dir(
164 dir: &str,
165 rest: &str,
166 ctx: &ResolveContext<'_>,
167) -> Result<PathBuf, ResolveError> {
168 let base = if is_absolute_install_name(dir) {
169 resolve_absolute(dir, ctx)?
170 } else {
171 join_allow_dotdot(ctx.loader_dir, dir)?
172 };
173 let candidate = join_no_dotdot(&base, rest)?;
174 ensure_allowlisted(&candidate, ctx)?;
175 Ok(candidate)
176}
177
178fn expand_rpath_value(rpath: &str, ctx: &ResolveContext<'_>) -> Result<PathBuf, ResolveError> {
179 if rpath.is_empty() {
180 return Err(ResolveError::Empty);
181 }
182 if let Some(rest) = rpath.strip_prefix("@executable_path/") {
183 join_allow_dotdot(ctx.executable_dir, rest)
185 } else if rpath == "@executable_path" {
186 Ok(ctx.executable_dir.to_path_buf())
187 } else if let Some(rest) = rpath.strip_prefix("@loader_path/") {
188 join_allow_dotdot(ctx.loader_dir, rest)
189 } else if rpath == "@loader_path" {
190 Ok(ctx.loader_dir.to_path_buf())
191 } else if rpath.starts_with('@') {
192 Err(ResolveError::Escape(rpath.to_owned()))
193 } else if is_absolute_install_name(rpath) {
194 resolve_absolute(rpath, ctx)
195 } else {
196 join_allow_dotdot(ctx.loader_dir, rpath)
198 }
199}
200
201fn join_no_dotdot(base: &Path, rest: &str) -> Result<PathBuf, ResolveError> {
202 join_path(base, rest, false)
203}
204
205fn join_path(base: &Path, rest: &str, allow_parent: bool) -> Result<PathBuf, ResolveError> {
212 if rest.is_empty() {
213 return Ok(base.to_path_buf());
214 }
215 let mut out = base.to_path_buf();
216 for comp in Path::new(rest).components() {
217 match comp {
218 Component::Normal(s) => out.push(s),
219 Component::CurDir => {}
220 Component::ParentDir if allow_parent => {
221 if !out.pop() {
222 return Err(ResolveError::Escape(rest.to_owned()));
223 }
224 }
225 Component::ParentDir | Component::Prefix(_) | Component::RootDir => {
226 return Err(ResolveError::Escape(rest.to_owned()));
227 }
228 }
229 }
230 Ok(out)
231}
232
233fn join_allow_dotdot(base: &Path, rest: &str) -> Result<PathBuf, ResolveError> {
235 join_path(base, rest, true)
236}
237
238fn ensure_allowlisted(host: &Path, ctx: &ResolveContext<'_>) -> Result<(), ResolveError> {
243 let check = path_for_allowlist_check(host);
244
245 if let Some(root) = ctx.bottle_root {
246 let root_canon = canonicalize_or_owned(root);
247 if is_path_under(&check, &root_canon) {
248 return Ok(());
249 }
250 }
251
252 let exe_canon = canonicalize_or_owned(ctx.executable_dir);
253 if is_path_under(&check, &exe_canon) {
254 return Ok(());
255 }
256
257 Err(ResolveError::OutsideAllowlist(host.to_path_buf()))
258}
259
260fn path_for_allowlist_check(host: &Path) -> PathBuf {
261 if host.exists() {
262 return host
263 .canonicalize()
264 .unwrap_or_else(|_| lexical_normalize(host));
265 }
266 canonicalize_with_missing_tail(host)
268}
269
270fn canonicalize_with_missing_tail(host: &Path) -> PathBuf {
271 let mut components: Vec<_> = host.components().collect();
272 let mut tail = Vec::new();
273 while !components.is_empty() {
274 let prefix: PathBuf = components.iter().collect();
275 if prefix.exists() {
276 let mut base = prefix.canonicalize().unwrap_or(prefix);
277 for c in tail.into_iter().rev() {
278 base.push(c);
279 }
280 return base;
281 }
282 if let Some(Component::Normal(s)) = components.pop() {
283 tail.push(s.to_os_string());
284 } else {
285 break;
286 }
287 }
288 lexical_normalize(host)
289}
290
291fn canonicalize_or_owned(path: &Path) -> PathBuf {
292 path.canonicalize().unwrap_or_else(|_| path.to_path_buf())
293}
294
295fn lexical_normalize(path: &Path) -> PathBuf {
296 let mut out = PathBuf::new();
297 for comp in path.components() {
298 match comp {
299 Component::ParentDir => {
300 let _ = out.pop();
301 }
302 Component::CurDir => {}
303 other => out.push(other.as_os_str()),
304 }
305 }
306 out
307}
308
309fn is_path_under(path: &Path, base: &Path) -> bool {
310 path.starts_with(base)
311}
312
313fn path_err_to_resolve(err: kh_runtime::PathError) -> ResolveError {
314 match err {
315 kh_runtime::PathError::Empty => ResolveError::Empty,
316 kh_runtime::PathError::Escape(s) => ResolveError::Escape(s),
317 kh_runtime::PathError::InvalidEncoding => ResolveError::InvalidEncoding,
318 }
319}
320
321#[cfg(test)]
322#[allow(clippy::expect_used, clippy::unwrap_used)]
323mod tests {
324 use super::*;
325 use std::fs::{self, File};
326 use std::io::Write;
327
328 fn ctx<'a>(
329 bottle: Option<&'a Path>,
330 exe_dir: &'a Path,
331 loader_dir: &'a Path,
332 rpaths: &'a [String],
333 ) -> ResolveContext<'a> {
334 ResolveContext {
335 bottle_root: bottle,
336 executable_dir: exe_dir,
337 loader_dir,
338 rpaths,
339 }
340 }
341
342 #[test]
343 fn absolute_without_bottle_is_no_bottle() {
344 let exe = Path::new("/tmp/kh-exe-dir");
345 let c = ctx(None, exe, exe, &[]);
346 let err = resolve_install_name("/usr/lib/libSystem.B.dylib", &c).unwrap_err();
347 assert_eq!(err, ResolveError::NoBottle);
348 }
349
350 #[test]
351 fn absolute_with_bottle_under_root() {
352 let root = std::env::temp_dir().join(format!("kh-resolve-bottle-{}", std::process::id()));
353 let lib_dir = root.join("usr/lib");
354 fs::create_dir_all(&lib_dir).unwrap();
355 let lib = lib_dir.join("libFoo.dylib");
356 File::create(&lib).unwrap().write_all(b"x").unwrap();
357
358 let exe = root.join("bin");
359 fs::create_dir_all(&exe).unwrap();
360
361 let c = ctx(Some(root.as_path()), &exe, &exe, &[]);
362 let host = resolve_install_name("/usr/lib/libFoo.dylib", &c).unwrap();
363 assert_eq!(host, lib);
364 drop(fs::remove_dir_all(root));
365 }
366
367 #[test]
368 fn executable_path_relative() {
369 let dir = std::env::temp_dir().join(format!("kh-resolve-exe-{}", std::process::id()));
370 fs::create_dir_all(&dir).unwrap();
371 let dylib = dir.join("libkh_add.dylib");
372 File::create(&dylib).unwrap().write_all(b"x").unwrap();
373
374 let c = ctx(None, &dir, &dir, &[]);
375 let host = resolve_install_name("@executable_path/libkh_add.dylib", &c).unwrap();
376 assert_eq!(host, dylib);
377 drop(fs::remove_dir_all(dir));
378 }
379
380 #[test]
381 fn loader_path_relative() {
382 let exe_dir =
384 std::env::temp_dir().join(format!("kh-resolve-loader-{}", std::process::id()));
385 let loader = exe_dir.join("Frameworks");
386 fs::create_dir_all(&loader).unwrap();
387 let dylib = loader.join("Inner.dylib");
388 File::create(&dylib).unwrap().write_all(b"x").unwrap();
389
390 let c = ctx(None, &exe_dir, &loader, &[]);
391 let host = resolve_install_name("@loader_path/Inner.dylib", &c).unwrap();
392 assert_eq!(host, dylib);
393 drop(fs::remove_dir_all(exe_dir));
394 }
395
396 #[test]
397 fn rpath_first_hit() {
398 let dir = std::env::temp_dir().join(format!("kh-resolve-rpath-{}", std::process::id()));
399 let a = dir.join("a");
400 let b = dir.join("b");
401 fs::create_dir_all(&a).unwrap();
402 fs::create_dir_all(&b).unwrap();
403 let target = b.join("libX.dylib");
405 File::create(&target).unwrap().write_all(b"x").unwrap();
406
407 let rpaths = vec![
408 "@executable_path/a".to_owned(),
409 "@executable_path/b".to_owned(),
410 ];
411 let c = ctx(None, &dir, &dir, &rpaths);
412 let host = resolve_install_name("@rpath/libX.dylib", &c).unwrap();
413 assert_eq!(host, target);
414 drop(fs::remove_dir_all(dir));
415 }
416
417 #[test]
418 fn dotdot_outside_allowlist_rejected() {
419 let exe = Path::new("/tmp/kh-exe");
422 let c = ctx(None, exe, exe, &[]);
423 let err = resolve_install_name("@executable_path/../etc/passwd", &c).unwrap_err();
424 assert!(
425 matches!(err, ResolveError::OutsideAllowlist(_)),
426 "expected OutsideAllowlist, got {err:?}"
427 );
428 }
429
430 #[test]
431 fn rpath_executable_parent_lib_under_bottle() {
432 let root =
435 std::env::temp_dir().join(format!("kh-resolve-clt-rpath-{}", std::process::id()));
436 let bin = root.join("usr/bin");
437 let lib = root.join("usr/lib");
438 fs::create_dir_all(&bin).unwrap();
439 fs::create_dir_all(&lib).unwrap();
440 let tapi = lib.join("libtapi.dylib");
441 File::create(&tapi).unwrap().write_all(b"x").unwrap();
442
443 let rpaths = vec!["@executable_path/../lib".to_owned()];
444 let c = ctx(Some(root.as_path()), &bin, &bin, &rpaths);
445 let host = resolve_install_name("@rpath/libtapi.dylib", &c).unwrap();
446 assert_eq!(host, tapi);
447 drop(fs::remove_dir_all(root));
448 }
449
450 #[test]
451 fn bottle_symlink_escape_rejected() {
452 let root = std::env::temp_dir().join(format!("kh-resolve-symlink-{}", std::process::id()));
453 let outside =
454 std::env::temp_dir().join(format!("kh-resolve-outside-{}", std::process::id()));
455 fs::create_dir_all(&root).unwrap();
456 fs::create_dir_all(&outside).unwrap();
457 let outside_lib = outside.join("evil.dylib");
458 File::create(&outside_lib).unwrap().write_all(b"x").unwrap();
459
460 let link = root.join("escape.dylib");
461 #[cfg(unix)]
462 std::os::unix::fs::symlink(&outside_lib, &link).unwrap();
463
464 let exe = root.join("bin");
465 fs::create_dir_all(&exe).unwrap();
466
467 let c = ctx(Some(root.as_path()), &exe, &exe, &[]);
468 let result = resolve_install_name("/escape.dylib", &c);
471 assert!(
472 matches!(result, Err(ResolveError::OutsideAllowlist(_))),
473 "expected OutsideAllowlist, got {result:?}"
474 );
475
476 drop(fs::remove_dir_all(root));
477 drop(fs::remove_dir_all(outside));
478 }
479
480 #[test]
481 fn absolute_planted_host_path_still_no_bottle() {
482 let planted =
485 std::env::temp_dir().join(format!("kh-fake-libsystem-{}", std::process::id()));
486 File::create(&planted).unwrap().write_all(b"x").unwrap();
487 let abs = planted.to_str().expect("utf8 temp path");
488 let exe = Path::new("/tmp/kh-exe-dir");
489 let c = ctx(None, exe, exe, &[]);
490 let err = resolve_install_name(abs, &c).unwrap_err();
491 assert_eq!(err, ResolveError::NoBottle);
492 drop(fs::remove_file(planted));
493 }
494}