1use std::path::{Path, PathBuf};
9
10use thiserror::Error;
11
12use super::layout;
13use super::libsystem::{self, LibsystemInstall, LibsystemOrigin};
14use super::registry;
15
16static EMBEDDED_LIBSYSTEM: &[u8] = include_bytes!("../../resources/libSystem.B.dylib");
20
21#[derive(Debug, Error)]
23pub enum BottleError {
24 #[error(
26 "a bottle already exists at {path}\n\
27 create a new one only after deleting the current bottle:\n\
28 kh bottle destroy"
29 )]
30 AlreadyExists {
31 path: PathBuf,
33 },
34
35 #[error("no bottle is registered (nothing to destroy)")]
37 NotRegistered,
38
39 #[error("path is not a kakehashi bottle (missing marker): {0}")]
41 NotABottle(PathBuf),
42
43 #[error("destroy cancelled (confirmation required)")]
45 NotConfirmed,
46
47 #[error("libSystem source not found: {0}")]
49 LibsystemNotFound(PathBuf),
50
51 #[error(transparent)]
53 Io(#[from] std::io::Error),
54}
55
56#[derive(Debug, Clone, PartialEq, Eq)]
58#[allow(clippy::struct_excessive_bools)] pub struct BottleStatus {
60 pub path: PathBuf,
62 pub exists: bool,
64 pub valid_marker: bool,
66 pub libsystem: bool,
68 pub libcxx_alias: bool,
70}
71
72#[derive(Debug, Clone, Default)]
74pub struct CreateOptions<'a> {
75 pub path: Option<&'a Path>,
77 pub libsystem: Option<&'a Path>,
79 pub skip_libsystem: bool,
81}
82
83#[derive(Debug, Clone, PartialEq, Eq)]
85pub struct CreateResult {
86 pub path: PathBuf,
88 pub libsystem: Option<LibsystemInstall>,
90}
91
92pub fn create(path: Option<&Path>) -> Result<CreateResult, BottleError> {
102 create_with(&CreateOptions {
103 path,
104 ..CreateOptions::default()
105 })
106}
107
108pub fn create_with(opts: &CreateOptions<'_>) -> Result<CreateResult, BottleError> {
110 if let Some(active) = registry::read_active()? {
111 if active.exists() {
112 return Err(BottleError::AlreadyExists { path: active });
113 }
114 registry::clear_active()?;
116 }
117
118 let target = match opts.path {
119 Some(p) => absolute(p)?,
120 None => registry::default_bottle_path()?,
121 };
122
123 if layout::is_bottle_root(&target) {
124 return Err(BottleError::AlreadyExists { path: target });
128 }
129
130 if target.exists() && target.read_dir()?.next().is_some() {
131 return Err(BottleError::Io(std::io::Error::new(
133 std::io::ErrorKind::AlreadyExists,
134 format!(
135 "refusing to create bottle in non-empty directory: {}",
136 target.display()
137 ),
138 )));
139 }
140
141 layout::materialize(&target)?;
142
143 let libsystem = match install_libsystem_for_create(&target, opts) {
144 Ok(v) => v,
145 Err(err) => {
146 drop(layout::remove_tree(&target));
147 return Err(err);
148 }
149 };
150
151 registry::write_active(&target)?;
152 Ok(CreateResult {
153 path: target,
154 libsystem,
155 })
156}
157
158fn install_libsystem_for_create(
159 target: &Path,
160 opts: &CreateOptions<'_>,
161) -> Result<Option<LibsystemInstall>, BottleError> {
162 if opts.skip_libsystem {
163 return Ok(None);
164 }
165 if let Some(explicit) = opts.libsystem {
166 if !explicit.is_file() {
167 return Err(BottleError::LibsystemNotFound(explicit.to_path_buf()));
168 }
169 return Ok(Some(libsystem::install(
170 target,
171 explicit,
172 LibsystemOrigin::Explicit,
173 )?));
174 }
175 if let Some((src, origin)) = libsystem::discover(None) {
176 return Ok(Some(libsystem::install(target, &src, origin)?));
177 }
178
179 if !EMBEDDED_LIBSYSTEM.is_empty() {
181 return Ok(Some(libsystem::install_bytes(
182 target,
183 EMBEDDED_LIBSYSTEM,
184 LibsystemOrigin::Embedded,
185 )?));
186 }
187
188 Ok(None)
189}
190
191pub fn destroy(confirmed: bool) -> Result<PathBuf, BottleError> {
196 let Some(path) = registry::read_active()? else {
197 return Err(BottleError::NotRegistered);
198 };
199
200 if !confirmed {
201 return Err(BottleError::NotConfirmed);
202 }
203
204 if path.exists() {
205 if layout::is_bottle_root(&path) {
206 layout::remove_tree(&path)?;
207 } else if path.is_dir() {
208 return Err(BottleError::NotABottle(path));
210 }
211 }
213
214 registry::clear_active()?;
215 Ok(path)
216}
217
218pub fn status() -> Result<Option<BottleStatus>, BottleError> {
220 let Some(path) = registry::read_active()? else {
221 return Ok(None);
222 };
223 let exists = path.exists();
224 let valid_marker = exists && layout::is_bottle_root(&path);
225 let libsystem = exists && path.join(libsystem::GUEST_LIBSYSTEM_REL).is_file();
226 let libcxx_alias = exists && layout::has_libcxx_symlink(&path);
227 Ok(Some(BottleStatus {
228 path,
229 exists,
230 valid_marker,
231 libsystem,
232 libcxx_alias,
233 }))
234}
235
236pub fn active_root() -> Result<Option<PathBuf>, BottleError> {
240 match status()? {
241 Some(s) if s.exists && s.valid_marker => Ok(Some(s.path)),
242 _ => Ok(None),
243 }
244}
245
246pub fn ensure(opts: &CreateOptions<'_>) -> Result<CreateResult, BottleError> {
261 if let Some(path) = active_root()? {
262 return refresh_bottle(&path, opts);
263 }
264
265 if let Some(p) = opts.path {
268 let abs = absolute(p)?;
269 if layout::is_bottle_root(&abs) {
270 return refresh_bottle(&abs, opts);
271 }
272 } else if let Ok(def) = registry::default_bottle_path()
273 && layout::is_bottle_root(&def)
274 {
275 return refresh_bottle(&def, opts);
276 }
277
278 create_with(opts)
279}
280
281fn refresh_bottle(path: &Path, opts: &CreateOptions<'_>) -> Result<CreateResult, BottleError> {
282 layout::ensure_libcxx_symlink(path)?;
283 let libsystem = install_libsystem_for_create(path, opts)?;
284 registry::write_active(path)?;
285 Ok(CreateResult {
286 path: path.to_path_buf(),
287 libsystem,
288 })
289}
290
291fn absolute(path: &Path) -> Result<PathBuf, BottleError> {
292 if path.is_absolute() {
293 return Ok(path.to_path_buf());
294 }
295 let cwd = std::env::current_dir()?;
296 Ok(cwd.join(path))
297}
298
299#[cfg(test)]
300#[allow(clippy::expect_used, clippy::panic, unsafe_code)]
301mod tests {
302 use super::*;
303 use crate::bottle::registry::test_env_lock;
304 use std::sync::atomic::{AtomicU64, Ordering};
305
306 fn unique(prefix: &str) -> PathBuf {
307 static N: AtomicU64 = AtomicU64::new(0);
308 let n = N.fetch_add(1, Ordering::Relaxed);
309 std::env::temp_dir().join(format!("kh-manage-{}-{}-{n}", prefix, std::process::id()))
310 }
311
312 struct EnvGuard {
313 cfg: PathBuf,
314 data: PathBuf,
315 }
316
317 impl EnvGuard {
318 fn new() -> Self {
319 let cfg = unique("cfg");
320 let data = unique("data");
321 drop(std::fs::remove_dir_all(&cfg));
322 drop(std::fs::remove_dir_all(&data));
323 std::fs::create_dir_all(&cfg).expect("cfg");
324 std::fs::create_dir_all(&data).expect("data");
325 unsafe {
327 std::env::set_var("KAKEHASHI_CONFIG_DIR", &cfg);
328 std::env::set_var("KAKEHASHI_DATA_DIR", &data);
329 }
330 Self { cfg, data }
331 }
332 }
333
334 impl Drop for EnvGuard {
335 fn drop(&mut self) {
336 unsafe {
338 std::env::remove_var("KAKEHASHI_CONFIG_DIR");
339 std::env::remove_var("KAKEHASHI_DATA_DIR");
340 }
341 drop(std::fs::remove_dir_all(&self.cfg));
342 drop(std::fs::remove_dir_all(&self.data));
343 }
344 }
345
346 #[test]
347 fn create_default_then_second_fails() {
348 let _lock = test_env_lock();
349 let g = EnvGuard::new();
350
351 let created = create_with(&CreateOptions {
352 skip_libsystem: true,
353 ..CreateOptions::default()
354 })
355 .expect("create");
356 let path = created.path;
357 assert!(layout::is_bottle_root(&path));
358 assert_eq!(path, g.data.join("bottle"));
359 assert!(path.join("Volumes/linux").is_symlink());
360 assert!(created.libsystem.is_none());
361
362 let err = create(None).expect_err("second create");
363 assert!(matches!(err, BottleError::AlreadyExists { .. }));
364
365 let destroyed = destroy(true).expect("destroy");
366 assert_eq!(destroyed, path);
367 assert!(!path.exists());
368 assert!(status().expect("status").is_none());
369 }
370
371 #[test]
372 fn create_custom_path_and_rename_survives_registry_update() {
373 let _lock = test_env_lock();
374 let _g = EnvGuard::new();
375
376 let custom = unique("custom-bottle-name");
377 let created = create_with(&CreateOptions {
378 path: Some(&custom),
379 skip_libsystem: true,
380 ..CreateOptions::default()
381 })
382 .expect("create custom");
383 let path = created.path;
384 assert_eq!(path, custom);
385 assert!(layout::is_bottle_root(&path));
386
387 let renamed = unique("renamed-by-user");
389 std::fs::rename(&path, &renamed).expect("rename");
390 let st = status().expect("status").expect("some");
392 assert!(!st.exists);
393
394 let again = unique("after-rename");
396 let path2 = create_with(&CreateOptions {
397 path: Some(&again),
398 skip_libsystem: true,
399 ..CreateOptions::default()
400 })
401 .expect("create after stale");
402 assert!(layout::is_bottle_root(&path2.path));
403
404 destroy(true).expect("destroy");
405 drop(std::fs::remove_dir_all(&renamed));
406 }
407
408 #[test]
409 fn destroy_requires_confirmation() {
410 let _lock = test_env_lock();
411 let _g = EnvGuard::new();
412
413 let path = create_with(&CreateOptions {
414 skip_libsystem: true,
415 ..CreateOptions::default()
416 })
417 .expect("create")
418 .path;
419 let err = destroy(false).expect_err("need confirm");
420 assert!(matches!(err, BottleError::NotConfirmed));
421 assert!(path.exists());
422 destroy(true).expect("destroy");
423 }
424
425 #[test]
426 fn volumes_linux_rw_outside_bottle() {
427 let _lock = test_env_lock();
428 let _g = EnvGuard::new();
429
430 let root = create_with(&CreateOptions {
431 skip_libsystem: true,
432 ..CreateOptions::default()
433 })
434 .expect("create")
435 .path;
436 let token = format!("kh-manage-vol-{}", std::process::id());
437 let host_file = std::env::temp_dir().join(&token);
438 let payload = b"rw-outside\n";
439 std::fs::write(&host_file, payload).expect("host write");
440
441 let via = root
442 .join(layout::VOLUMES_LINUX)
443 .join(host_file.strip_prefix("/").expect("abs"));
444 assert_eq!(std::fs::read(&via).expect("via read"), payload);
445
446 let payload2 = b"from-bottle-side\n";
447 std::fs::write(&via, payload2).expect("via write");
448 assert_eq!(std::fs::read(&host_file).expect("host read"), payload2);
449
450 drop(std::fs::remove_file(&host_file));
451 destroy(true).expect("destroy");
452 }
453
454 #[test]
455 fn create_installs_explicit_libsystem() {
456 let _lock = test_env_lock();
457 let _g = EnvGuard::new();
458
459 let repo = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../..");
461 let fixture = repo.join("tests/fixtures/bottle/usr/lib/libSystem.B.dylib");
462 assert!(fixture.is_file(), "missing fixture {}", fixture.display());
463
464 let created = create_with(&CreateOptions {
465 libsystem: Some(&fixture),
466 ..CreateOptions::default()
467 })
468 .expect("create with libsystem");
469 assert!(created.libsystem.is_some());
470 let dest = created.path.join(libsystem::GUEST_LIBSYSTEM_REL);
471 assert!(dest.is_file());
472 let st = status().expect("status").expect("registered");
473 assert!(st.libsystem);
474 assert!(st.libcxx_alias);
475 assert!(layout::has_libcxx_symlink(&created.path));
476
477 destroy(true).expect("destroy");
478 }
479
480 #[test]
481 fn ensure_creates_then_refreshes_libsystem() {
482 let _lock = test_env_lock();
483 let _g = EnvGuard::new();
484
485 let repo = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../..");
486 let fixture = repo.join("tests/fixtures/bottle/usr/lib/libSystem.B.dylib");
487 assert!(fixture.is_file());
488
489 let first = ensure(&CreateOptions {
490 libsystem: Some(&fixture),
491 ..CreateOptions::default()
492 })
493 .expect("ensure create");
494 assert!(first.libsystem.is_some());
495 let dest = first.path.join(libsystem::GUEST_LIBSYSTEM_REL);
496 let before = std::fs::metadata(&dest).expect("meta").len();
497
498 let second = ensure(&CreateOptions {
500 libsystem: Some(&fixture),
501 ..CreateOptions::default()
502 })
503 .expect("ensure refresh");
504 assert_eq!(second.path, first.path);
505 assert!(second.libsystem.is_some());
506 assert!(dest.is_file());
507 let after = std::fs::metadata(&dest).expect("meta2").len();
508 assert_eq!(before, after);
509
510 destroy(true).expect("destroy");
511 }
512}