Skip to main content

kh_runtime/bottle/
manage.rs

1//! Create / destroy / query the single Kakehashi bottle.
2
3use std::path::{Path, PathBuf};
4
5use thiserror::Error;
6
7use super::layout;
8use super::libsystem::{self, LibsystemInstall, LibsystemOrigin};
9use super::registry;
10
11/// Bottle management errors.
12#[derive(Debug, Error)]
13pub enum BottleError {
14    /// A bottle is already registered (create refused).
15    #[error(
16        "a bottle already exists at {path}\n\
17         create a new one only after deleting the current bottle:\n\
18           kh bottle destroy"
19    )]
20    AlreadyExists {
21        /// Absolute path of the existing bottle.
22        path: PathBuf,
23    },
24
25    /// Destroy requested but no bottle is registered.
26    #[error("no bottle is registered (nothing to destroy)")]
27    NotRegistered,
28
29    /// Registry points at a path that is not a valid bottle.
30    #[error("path is not a kakehashi bottle (missing marker): {0}")]
31    NotABottle(PathBuf),
32
33    /// Destroy refused because confirmation was not given.
34    #[error("destroy cancelled (confirmation required)")]
35    NotConfirmed,
36
37    /// `--libsystem` / env pointed at a path that is not a readable file.
38    #[error("libSystem source not found: {0}")]
39    LibsystemNotFound(PathBuf),
40
41    /// Underlying I/O failure.
42    #[error(transparent)]
43    Io(#[from] std::io::Error),
44}
45
46/// Snapshot of the registered bottle.
47#[derive(Debug, Clone, PartialEq, Eq)]
48#[allow(clippy::struct_excessive_bools)] // independent presence flags for CLI/status
49pub struct BottleStatus {
50    /// Absolute path from the registry (directory name is user-chosen).
51    pub path: PathBuf,
52    /// Whether the path exists on disk.
53    pub exists: bool,
54    /// Whether the path has a valid `.kakehashi-bottle` marker.
55    pub valid_marker: bool,
56    /// Whether `{path}/usr/lib/libSystem.B.dylib` is present.
57    pub libsystem: bool,
58    /// Whether `{path}/usr/lib/libc++.1.dylib` → `libSystem.B.dylib` alias exists.
59    pub libcxx_alias: bool,
60}
61
62/// Options for [`create`].
63#[derive(Debug, Clone, Default)]
64pub struct CreateOptions<'a> {
65    /// Bottle directory (default data path when `None`).
66    pub path: Option<&'a Path>,
67    /// Explicit guest dylib to install (`--libsystem`).
68    pub libsystem: Option<&'a Path>,
69    /// Skip searching/installing libSystem (skeleton only).
70    pub skip_libsystem: bool,
71}
72
73/// Result of a successful [`create`].
74#[derive(Debug, Clone, PartialEq, Eq)]
75pub struct CreateResult {
76    /// Absolute bottle root.
77    pub path: PathBuf,
78    /// libSystem install details when a source was found and copied.
79    pub libsystem: Option<LibsystemInstall>,
80}
81
82/// Creates the single bottle at `path` (or the default data path when `None`).
83///
84/// Fails if a bottle is already registered and still present on disk. A stale
85/// registry entry (path missing) is cleared automatically so create can proceed.
86///
87/// After the skeleton is written, installs guest `libSystem.B.dylib` when a
88/// source is discovered (see [`libsystem::discover`]) unless
89/// [`CreateOptions::skip_libsystem`] is set. An explicit `--libsystem` path that
90/// does not exist is an error; a missing auto-discovered source is not (the
91/// bottle is still usable for path tests without dylibs).
92pub fn create(path: Option<&Path>) -> Result<CreateResult, BottleError> {
93    create_with(&CreateOptions {
94        path,
95        ..CreateOptions::default()
96    })
97}
98
99/// Creates a bottle with full options (libSystem path / skip).
100pub fn create_with(opts: &CreateOptions<'_>) -> Result<CreateResult, BottleError> {
101    if let Some(active) = registry::read_active()? {
102        if active.exists() {
103            return Err(BottleError::AlreadyExists { path: active });
104        }
105        // Stale pointer — drop it and continue.
106        registry::clear_active()?;
107    }
108
109    let target = match opts.path {
110        Some(p) => absolute(p)?,
111        None => registry::default_bottle_path()?,
112    };
113
114    if layout::is_bottle_root(&target) {
115        // Directory looks like a bottle but was not registered — refuse to
116        // clobber; register it only after explicit destroy of its tree, or
117        // treat as already-exists at that path.
118        return Err(BottleError::AlreadyExists { path: target });
119    }
120
121    if target.exists() && target.read_dir()?.next().is_some() {
122        // Non-empty non-bottle directory: do not silently overwrite.
123        return Err(BottleError::Io(std::io::Error::new(
124            std::io::ErrorKind::AlreadyExists,
125            format!(
126                "refusing to create bottle in non-empty directory: {}",
127                target.display()
128            ),
129        )));
130    }
131
132    layout::materialize(&target)?;
133
134    let libsystem = match install_libsystem_for_create(&target, opts) {
135        Ok(v) => v,
136        Err(err) => {
137            drop(layout::remove_tree(&target));
138            return Err(err);
139        }
140    };
141
142    registry::write_active(&target)?;
143    Ok(CreateResult {
144        path: target,
145        libsystem,
146    })
147}
148
149fn install_libsystem_for_create(
150    target: &Path,
151    opts: &CreateOptions<'_>,
152) -> Result<Option<LibsystemInstall>, BottleError> {
153    if opts.skip_libsystem {
154        return Ok(None);
155    }
156    if let Some(explicit) = opts.libsystem {
157        if !explicit.is_file() {
158            return Err(BottleError::LibsystemNotFound(explicit.to_path_buf()));
159        }
160        return Ok(Some(libsystem::install(
161            target,
162            explicit,
163            LibsystemOrigin::Explicit,
164        )?));
165    }
166    if let Some((src, origin)) = libsystem::discover(None) {
167        return Ok(Some(libsystem::install(target, &src, origin)?));
168    }
169    Ok(None)
170}
171
172/// Destroys the registered bottle after `confirmed` is true.
173///
174/// When `confirmed` is false, returns [`BottleError::NotConfirmed`] without
175/// touching the filesystem (CLI prompts, then retries with `true`).
176pub fn destroy(confirmed: bool) -> Result<PathBuf, BottleError> {
177    let Some(path) = registry::read_active()? else {
178        return Err(BottleError::NotRegistered);
179    };
180
181    if !confirmed {
182        return Err(BottleError::NotConfirmed);
183    }
184
185    if path.exists() {
186        if layout::is_bottle_root(&path) {
187            layout::remove_tree(&path)?;
188        } else if path.is_dir() {
189            // Registry path exists but marker missing — refuse blind rm -rf.
190            return Err(BottleError::NotABottle(path));
191        }
192        // If path is a leftover file or already gone after check, still clear.
193    }
194
195    registry::clear_active()?;
196    Ok(path)
197}
198
199/// Returns status of the registered bottle, if any.
200pub fn status() -> Result<Option<BottleStatus>, BottleError> {
201    let Some(path) = registry::read_active()? else {
202        return Ok(None);
203    };
204    let exists = path.exists();
205    let valid_marker = exists && layout::is_bottle_root(&path);
206    let libsystem = exists && path.join(libsystem::GUEST_LIBSYSTEM_REL).is_file();
207    let libcxx_alias = exists && layout::has_libcxx_symlink(&path);
208    Ok(Some(BottleStatus {
209        path,
210        exists,
211        valid_marker,
212        libsystem,
213        libcxx_alias,
214    }))
215}
216
217/// Returns the active bottle path when registered and valid on disk.
218///
219/// Used by CLI root resolution as a fallback after `--root` / `KAKEHASHI_ROOT`.
220pub fn active_root() -> Result<Option<PathBuf>, BottleError> {
221    match status()? {
222        Some(s) if s.exists && s.valid_marker => Ok(Some(s.path)),
223        _ => Ok(None),
224    }
225}
226
227/// Idempotent bottle setup: create when missing, refresh libSystem when present.
228///
229/// Intended for Docker/dev loops so you never hand-assemble `.tmp-bottle` trees:
230///
231/// ```text
232/// kh bottle ensure --libsystem dist/guest/libSystem.B.dylib
233/// kh run tests/clang-probe/7zz.bin -- --help   # uses registered bottle
234/// ```
235///
236/// * Valid registered bottle → reinstalls libSystem (unless `skip_libsystem`).
237/// * Unregistered path that already has a bottle marker → adopt + refresh.
238/// * Otherwise → same as [`create_with`].
239/// * Explicit `--libsystem` that is missing is always an error.
240pub fn ensure(opts: &CreateOptions<'_>) -> Result<CreateResult, BottleError> {
241    if let Some(path) = active_root()? {
242        return refresh_bottle(&path, opts);
243    }
244
245    // Adopt a marker'd bottle that is not in the registry (e.g. after wiping
246    // KAKEHASHI_CONFIG_DIR but keeping the tree, or a previous manual path).
247    if let Some(p) = opts.path {
248        let abs = absolute(p)?;
249        if layout::is_bottle_root(&abs) {
250            return refresh_bottle(&abs, opts);
251        }
252    } else if let Ok(def) = registry::default_bottle_path()
253        && layout::is_bottle_root(&def)
254    {
255        return refresh_bottle(&def, opts);
256    }
257
258    create_with(opts)
259}
260
261fn refresh_bottle(path: &Path, opts: &CreateOptions<'_>) -> Result<CreateResult, BottleError> {
262    layout::ensure_libcxx_symlink(path)?;
263    let libsystem = install_libsystem_for_create(path, opts)?;
264    registry::write_active(path)?;
265    Ok(CreateResult {
266        path: path.to_path_buf(),
267        libsystem,
268    })
269}
270
271fn absolute(path: &Path) -> Result<PathBuf, BottleError> {
272    if path.is_absolute() {
273        return Ok(path.to_path_buf());
274    }
275    let cwd = std::env::current_dir()?;
276    Ok(cwd.join(path))
277}
278
279#[cfg(test)]
280#[allow(clippy::expect_used, clippy::panic, unsafe_code)]
281mod tests {
282    use super::*;
283    use crate::bottle::registry::test_env_lock;
284    use std::sync::atomic::{AtomicU64, Ordering};
285
286    fn unique(prefix: &str) -> PathBuf {
287        static N: AtomicU64 = AtomicU64::new(0);
288        let n = N.fetch_add(1, Ordering::Relaxed);
289        std::env::temp_dir().join(format!("kh-manage-{}-{}-{n}", prefix, std::process::id()))
290    }
291
292    struct EnvGuard {
293        cfg: PathBuf,
294        data: PathBuf,
295    }
296
297    impl EnvGuard {
298        fn new() -> Self {
299            let cfg = unique("cfg");
300            let data = unique("data");
301            drop(std::fs::remove_dir_all(&cfg));
302            drop(std::fs::remove_dir_all(&data));
303            std::fs::create_dir_all(&cfg).expect("cfg");
304            std::fs::create_dir_all(&data).expect("data");
305            // SAFETY: serialized by test_env_lock; EnvGuard restores on drop.
306            unsafe {
307                std::env::set_var("KAKEHASHI_CONFIG_DIR", &cfg);
308                std::env::set_var("KAKEHASHI_DATA_DIR", &data);
309            }
310            Self { cfg, data }
311        }
312    }
313
314    impl Drop for EnvGuard {
315        fn drop(&mut self) {
316            // SAFETY: paired with set_var in new(); still under test_env_lock.
317            unsafe {
318                std::env::remove_var("KAKEHASHI_CONFIG_DIR");
319                std::env::remove_var("KAKEHASHI_DATA_DIR");
320            }
321            drop(std::fs::remove_dir_all(&self.cfg));
322            drop(std::fs::remove_dir_all(&self.data));
323        }
324    }
325
326    #[test]
327    fn create_default_then_second_fails() {
328        let _lock = test_env_lock();
329        let g = EnvGuard::new();
330
331        let created = create_with(&CreateOptions {
332            skip_libsystem: true,
333            ..CreateOptions::default()
334        })
335        .expect("create");
336        let path = created.path;
337        assert!(layout::is_bottle_root(&path));
338        assert_eq!(path, g.data.join("bottle"));
339        assert!(path.join("Volumes/linux").is_symlink());
340        assert!(created.libsystem.is_none());
341
342        let err = create(None).expect_err("second create");
343        assert!(matches!(err, BottleError::AlreadyExists { .. }));
344
345        let destroyed = destroy(true).expect("destroy");
346        assert_eq!(destroyed, path);
347        assert!(!path.exists());
348        assert!(status().expect("status").is_none());
349    }
350
351    #[test]
352    fn create_custom_path_and_rename_survives_registry_update() {
353        let _lock = test_env_lock();
354        let _g = EnvGuard::new();
355
356        let custom = unique("custom-bottle-name");
357        let created = create_with(&CreateOptions {
358            path: Some(&custom),
359            skip_libsystem: true,
360            ..CreateOptions::default()
361        })
362        .expect("create custom");
363        let path = created.path;
364        assert_eq!(path, custom);
365        assert!(layout::is_bottle_root(&path));
366
367        // User renames the bottle directory — registry still points at old path.
368        let renamed = unique("renamed-by-user");
369        std::fs::rename(&path, &renamed).expect("rename");
370        // Stale: exists=false after rename of registered path.
371        let st = status().expect("status").expect("some");
372        assert!(!st.exists);
373
374        // Create should clear stale and succeed at a new path.
375        let again = unique("after-rename");
376        let path2 = create_with(&CreateOptions {
377            path: Some(&again),
378            skip_libsystem: true,
379            ..CreateOptions::default()
380        })
381        .expect("create after stale");
382        assert!(layout::is_bottle_root(&path2.path));
383
384        destroy(true).expect("destroy");
385        drop(std::fs::remove_dir_all(&renamed));
386    }
387
388    #[test]
389    fn destroy_requires_confirmation() {
390        let _lock = test_env_lock();
391        let _g = EnvGuard::new();
392
393        let path = create_with(&CreateOptions {
394            skip_libsystem: true,
395            ..CreateOptions::default()
396        })
397        .expect("create")
398        .path;
399        let err = destroy(false).expect_err("need confirm");
400        assert!(matches!(err, BottleError::NotConfirmed));
401        assert!(path.exists());
402        destroy(true).expect("destroy");
403    }
404
405    #[test]
406    fn volumes_linux_rw_outside_bottle() {
407        let _lock = test_env_lock();
408        let _g = EnvGuard::new();
409
410        let root = create_with(&CreateOptions {
411            skip_libsystem: true,
412            ..CreateOptions::default()
413        })
414        .expect("create")
415        .path;
416        let token = format!("kh-manage-vol-{}", std::process::id());
417        let host_file = std::env::temp_dir().join(&token);
418        let payload = b"rw-outside\n";
419        std::fs::write(&host_file, payload).expect("host write");
420
421        let via = root
422            .join(layout::VOLUMES_LINUX)
423            .join(host_file.strip_prefix("/").expect("abs"));
424        assert_eq!(std::fs::read(&via).expect("via read"), payload);
425
426        let payload2 = b"from-bottle-side\n";
427        std::fs::write(&via, payload2).expect("via write");
428        assert_eq!(std::fs::read(&host_file).expect("host read"), payload2);
429
430        drop(std::fs::remove_file(&host_file));
431        destroy(true).expect("destroy");
432    }
433
434    #[test]
435    fn create_installs_explicit_libsystem() {
436        let _lock = test_env_lock();
437        let _g = EnvGuard::new();
438
439        // Synthetic bottle fixture (checked in) is a valid thin arm64 dylib.
440        let repo = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../..");
441        let fixture = repo.join("tests/fixtures/bottle/usr/lib/libSystem.B.dylib");
442        assert!(fixture.is_file(), "missing fixture {}", fixture.display());
443
444        let created = create_with(&CreateOptions {
445            libsystem: Some(&fixture),
446            ..CreateOptions::default()
447        })
448        .expect("create with libsystem");
449        assert!(created.libsystem.is_some());
450        let dest = created.path.join(libsystem::GUEST_LIBSYSTEM_REL);
451        assert!(dest.is_file());
452        let st = status().expect("status").expect("registered");
453        assert!(st.libsystem);
454        assert!(st.libcxx_alias);
455        assert!(layout::has_libcxx_symlink(&created.path));
456
457        destroy(true).expect("destroy");
458    }
459
460    #[test]
461    fn ensure_creates_then_refreshes_libsystem() {
462        let _lock = test_env_lock();
463        let _g = EnvGuard::new();
464
465        let repo = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../..");
466        let fixture = repo.join("tests/fixtures/bottle/usr/lib/libSystem.B.dylib");
467        assert!(fixture.is_file());
468
469        let first = ensure(&CreateOptions {
470            libsystem: Some(&fixture),
471            ..CreateOptions::default()
472        })
473        .expect("ensure create");
474        assert!(first.libsystem.is_some());
475        let dest = first.path.join(libsystem::GUEST_LIBSYSTEM_REL);
476        let before = std::fs::metadata(&dest).expect("meta").len();
477
478        // Second ensure reuses the same bottle and reinstalls the dylib.
479        let second = ensure(&CreateOptions {
480            libsystem: Some(&fixture),
481            ..CreateOptions::default()
482        })
483        .expect("ensure refresh");
484        assert_eq!(second.path, first.path);
485        assert!(second.libsystem.is_some());
486        assert!(dest.is_file());
487        let after = std::fs::metadata(&dest).expect("meta2").len();
488        assert_eq!(before, after);
489
490        destroy(true).expect("destroy");
491    }
492}