Skip to main content

kh_runtime/bottle/
manage.rs

1//! Create / destroy / query the single Kakehashi bottle.
2//!
3//! Guest `libSystem.B.dylib` is installed from disk discovery first, then from
4//! the freestanding dylib **embedded** in this crate (`resources/libSystem.B.dylib`).
5//! That file is published on crates.io with `kh-runtime`, so
6//! `cargo install kakehashi` → `kh bottle ensure` needs no separate dylib.
7
8use std::path::{Path, PathBuf};
9
10use thiserror::Error;
11
12use super::layout;
13use super::libsystem::{self, LibsystemInstall, LibsystemOrigin};
14use super::registry;
15
16/// Freestanding guest libSystem shipped with this crate (crates.io / cargo install).
17///
18/// Refresh after rebuilding `kh-libsystem` with `./scripts/stage-libsystem.sh`.
19static EMBEDDED_LIBSYSTEM: &[u8] = include_bytes!("../../resources/libSystem.B.dylib");
20
21/// Bottle management errors.
22#[derive(Debug, Error)]
23pub enum BottleError {
24    /// A bottle is already registered (create refused).
25    #[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        /// Absolute path of the existing bottle.
32        path: PathBuf,
33    },
34
35    /// Destroy requested but no bottle is registered.
36    #[error("no bottle is registered (nothing to destroy)")]
37    NotRegistered,
38
39    /// Registry points at a path that is not a valid bottle.
40    #[error("path is not a kakehashi bottle (missing marker): {0}")]
41    NotABottle(PathBuf),
42
43    /// Destroy refused because confirmation was not given.
44    #[error("destroy cancelled (confirmation required)")]
45    NotConfirmed,
46
47    /// `--libsystem` / env pointed at a path that is not a readable file.
48    #[error("libSystem source not found: {0}")]
49    LibsystemNotFound(PathBuf),
50
51    /// Underlying I/O failure.
52    #[error(transparent)]
53    Io(#[from] std::io::Error),
54}
55
56/// Snapshot of the registered bottle.
57#[derive(Debug, Clone, PartialEq, Eq)]
58#[allow(clippy::struct_excessive_bools)] // independent presence flags for CLI/status
59pub struct BottleStatus {
60    /// Absolute path from the registry (directory name is user-chosen).
61    pub path: PathBuf,
62    /// Whether the path exists on disk.
63    pub exists: bool,
64    /// Whether the path has a valid `.kakehashi-bottle` marker.
65    pub valid_marker: bool,
66    /// Whether `{path}/usr/lib/libSystem.B.dylib` is present.
67    pub libsystem: bool,
68    /// Whether `{path}/usr/lib/libc++.1.dylib` → `libSystem.B.dylib` alias exists.
69    pub libcxx_alias: bool,
70}
71
72/// Options for [`create`].
73#[derive(Debug, Clone, Default)]
74pub struct CreateOptions<'a> {
75    /// Bottle directory (default data path when `None`).
76    pub path: Option<&'a Path>,
77    /// Explicit guest dylib to install (`--libsystem`).
78    pub libsystem: Option<&'a Path>,
79    /// Skip searching/installing libSystem (skeleton only).
80    pub skip_libsystem: bool,
81}
82
83/// Result of a successful [`create`].
84#[derive(Debug, Clone, PartialEq, Eq)]
85pub struct CreateResult {
86    /// Absolute bottle root.
87    pub path: PathBuf,
88    /// libSystem install details when a source was found and copied.
89    pub libsystem: Option<LibsystemInstall>,
90}
91
92/// Creates the single bottle at `path` (or the default data path when `None`).
93///
94/// Fails if a bottle is already registered and still present on disk. A stale
95/// registry entry (path missing) is cleared automatically so create can proceed.
96///
97/// After the skeleton is written, installs guest `libSystem.B.dylib` when a
98/// source is discovered (see [`libsystem::discover`]) or from the crate-embedded
99/// freestanding dylib, unless [`CreateOptions::skip_libsystem`] is set.
100/// An explicit `--libsystem` path that does not exist is an error.
101pub fn create(path: Option<&Path>) -> Result<CreateResult, BottleError> {
102    create_with(&CreateOptions {
103        path,
104        ..CreateOptions::default()
105    })
106}
107
108/// Creates a bottle with full options (libSystem path / skip).
109pub 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        // Stale pointer — drop it and continue.
115        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        // Directory looks like a bottle but was not registered — refuse to
125        // clobber; register it only after explicit destroy of its tree, or
126        // treat as already-exists at that path.
127        return Err(BottleError::AlreadyExists { path: target });
128    }
129
130    if target.exists() && target.read_dir()?.next().is_some() {
131        // Non-empty non-bottle directory: do not silently overwrite.
132        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    // crates.io / cargo install: freestanding dylib is vendored in this crate.
180    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
191/// Destroys the registered bottle after `confirmed` is true.
192///
193/// When `confirmed` is false, returns [`BottleError::NotConfirmed`] without
194/// touching the filesystem (CLI prompts, then retries with `true`).
195pub 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            // Registry path exists but marker missing — refuse blind rm -rf.
209            return Err(BottleError::NotABottle(path));
210        }
211        // If path is a leftover file or already gone after check, still clear.
212    }
213
214    registry::clear_active()?;
215    Ok(path)
216}
217
218/// Returns status of the registered bottle, if any.
219pub 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
236/// Returns the active bottle path when registered and valid on disk.
237///
238/// Used by CLI root resolution as a fallback after `--root` / `KAKEHASHI_ROOT`.
239pub 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
246/// Idempotent bottle setup: create when missing, refresh libSystem when present.
247///
248/// ```text
249/// # After cargo install kakehashi (uses embedded freestanding libSystem):
250/// kh bottle ensure
251///
252/// # Dev: override with a just-built dylib
253/// kh bottle ensure --libsystem dist/guest/libSystem.B.dylib
254/// ```
255///
256/// * Valid registered bottle → reinstalls libSystem (unless `skip_libsystem`).
257/// * Unregistered path that already has a bottle marker → adopt + refresh.
258/// * Otherwise → same as [`create_with`].
259/// * Explicit `--libsystem` that is missing is always an error.
260pub fn ensure(opts: &CreateOptions<'_>) -> Result<CreateResult, BottleError> {
261    if let Some(path) = active_root()? {
262        return refresh_bottle(&path, opts);
263    }
264
265    // Adopt a marker'd bottle that is not in the registry (e.g. after wiping
266    // KAKEHASHI_CONFIG_DIR but keeping the tree, or a previous manual path).
267    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            // SAFETY: serialized by test_env_lock; EnvGuard restores on drop.
326            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            // SAFETY: paired with set_var in new(); still under test_env_lock.
337            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        // User renames the bottle directory — registry still points at old path.
388        let renamed = unique("renamed-by-user");
389        std::fs::rename(&path, &renamed).expect("rename");
390        // Stale: exists=false after rename of registered path.
391        let st = status().expect("status").expect("some");
392        assert!(!st.exists);
393
394        // Create should clear stale and succeed at a new path.
395        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        // Synthetic bottle fixture (checked in) is a valid thin arm64 dylib.
460        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        // Second ensure reuses the same bottle and reinstalls the dylib.
499        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}