kh-runtime 0.1.14

Kakehashi native ARM64 execution context, memory layout, traps, and bottle
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
//! Create / destroy / query the single Kakehashi bottle.
//!
//! Guest `libSystem.B.dylib` is installed from disk discovery first, then from
//! the freestanding dylib **embedded** in this crate (`resources/libSystem.B.dylib`).
//! That file is published on crates.io with `kh-runtime`, so
//! `cargo install kakehashi` → `kh bottle ensure` needs no separate dylib.

use std::path::{Path, PathBuf};

use thiserror::Error;

use super::layout;
use super::libsystem::{self, LibsystemInstall, LibsystemOrigin};
use super::registry;
use super::xcrun_tool::{self, XcrunInstall, XcrunOrigin};

/// Freestanding guest libSystem shipped with this crate (crates.io / cargo install).
///
/// Refresh after rebuilding `kh-libsystem` with `./scripts/stage-libsystem.sh`.
static EMBEDDED_LIBSYSTEM: &[u8] = include_bytes!("../../resources/libSystem.B.dylib");

/// Clean-room guest `xcrun` shipped with this crate (crates.io / cargo install).
///
/// Refresh after rebuilding `kh-xcrun` with `./scripts/stage-xcrun.sh`.
/// Empty file is treated as "not embedded" so Linux-only checkouts without a
/// staged Mach-O still compile; `bottle ensure` then skips xcrun install.
static EMBEDDED_XCRUN: &[u8] = include_bytes!("../../resources/xcrun");

/// Bottle management errors.
#[derive(Debug, Error)]
pub enum BottleError {
    /// A bottle is already registered (create refused).
    #[error(
        "a bottle already exists at {path}\n\
         create a new one only after deleting the current bottle:\n\
           kh bottle destroy"
    )]
    AlreadyExists {
        /// Absolute path of the existing bottle.
        path: PathBuf,
    },

    /// Destroy requested but no bottle is registered.
    #[error("no bottle is registered (nothing to destroy)")]
    NotRegistered,

    /// Registry points at a path that is not a valid bottle.
    #[error("path is not a kakehashi bottle (missing marker): {0}")]
    NotABottle(PathBuf),

    /// Destroy refused because confirmation was not given.
    #[error("destroy cancelled (confirmation required)")]
    NotConfirmed,

    /// `--libsystem` / env pointed at a path that is not a readable file.
    #[error("libSystem source not found: {0}")]
    LibsystemNotFound(PathBuf),

    /// Underlying I/O failure.
    #[error(transparent)]
    Io(#[from] std::io::Error),
}

/// Snapshot of the registered bottle.
#[derive(Debug, Clone, PartialEq, Eq)]
#[allow(clippy::struct_excessive_bools)] // independent presence flags for CLI/status
pub struct BottleStatus {
    /// Absolute path from the registry (directory name is user-chosen).
    pub path: PathBuf,
    /// Whether the path exists on disk.
    pub exists: bool,
    /// Whether the path has a valid `.kakehashi-bottle` marker.
    pub valid_marker: bool,
    /// Whether `{path}/usr/lib/libSystem.B.dylib` is present.
    pub libsystem: bool,
    /// Whether `{path}/usr/lib/libc++.1.dylib` → `libSystem.B.dylib` alias exists.
    pub libcxx_alias: bool,
    /// Whether `{path}/usr/lib/libcurl.4.dylib` → `libSystem.B.dylib` alias exists.
    pub libcurl_alias: bool,
}

/// Options for [`create`].
#[derive(Debug, Clone, Default)]
pub struct CreateOptions<'a> {
    /// Bottle directory (default data path when `None`).
    pub path: Option<&'a Path>,
    /// Explicit guest dylib to install (`--libsystem`).
    pub libsystem: Option<&'a Path>,
    /// Skip searching/installing libSystem (skeleton only).
    pub skip_libsystem: bool,
}

/// Result of a successful [`create`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CreateResult {
    /// Absolute bottle root.
    pub path: PathBuf,
    /// libSystem install details when a source was found and copied.
    pub libsystem: Option<LibsystemInstall>,
    /// Guest `/usr/bin/xcrun` install details when a source was found.
    pub xcrun: Option<XcrunInstall>,
}

/// Creates the single bottle at `path` (or the default data path when `None`).
///
/// Fails if a bottle is already registered and still present on disk. A stale
/// registry entry (path missing) is cleared automatically so create can proceed.
///
/// After the skeleton is written, installs guest `libSystem.B.dylib` when a
/// source is discovered (see [`libsystem::discover`]) or from the crate-embedded
/// freestanding dylib, unless [`CreateOptions::skip_libsystem`] is set.
/// An explicit `--libsystem` path that does not exist is an error.
pub fn create(path: Option<&Path>) -> Result<CreateResult, BottleError> {
    create_with(&CreateOptions {
        path,
        ..CreateOptions::default()
    })
}

/// Creates a bottle with full options (libSystem path / skip).
pub fn create_with(opts: &CreateOptions<'_>) -> Result<CreateResult, BottleError> {
    if let Some(active) = registry::read_active()? {
        if active.exists() {
            return Err(BottleError::AlreadyExists { path: active });
        }
        // Stale pointer — drop it and continue.
        registry::clear_active()?;
    }

    let target = match opts.path {
        Some(p) => absolute(p)?,
        None => registry::default_bottle_path()?,
    };

    if layout::is_bottle_root(&target) {
        // Directory looks like a bottle but was not registered — refuse to
        // clobber; register it only after explicit destroy of its tree, or
        // treat as already-exists at that path.
        return Err(BottleError::AlreadyExists { path: target });
    }

    if target.exists() && target.read_dir()?.next().is_some() {
        // Non-empty non-bottle directory: do not silently overwrite.
        return Err(BottleError::Io(std::io::Error::new(
            std::io::ErrorKind::AlreadyExists,
            format!(
                "refusing to create bottle in non-empty directory: {}",
                target.display()
            ),
        )));
    }

    layout::materialize(&target)?;

    let libsystem = match install_libsystem_for_create(&target, opts) {
        Ok(v) => v,
        Err(err) => {
            drop(layout::remove_tree(&target));
            return Err(err);
        }
    };

    let xcrun = match install_xcrun_for_create(&target) {
        Ok(v) => v,
        Err(err) => {
            drop(layout::remove_tree(&target));
            return Err(err);
        }
    };

    if let Err(e) = super::ca_bundle::ensure_ca_bundle(&target) {
        tracing::warn!(error = %e, "failed to seed bottle CA bundle");
    }

    registry::write_active(&target)?;
    Ok(CreateResult {
        path: target,
        libsystem,
        xcrun,
    })
}

fn install_libsystem_for_create(
    target: &Path,
    opts: &CreateOptions<'_>,
) -> Result<Option<LibsystemInstall>, BottleError> {
    if opts.skip_libsystem {
        return Ok(None);
    }
    if let Some(explicit) = opts.libsystem {
        if !explicit.is_file() {
            return Err(BottleError::LibsystemNotFound(explicit.to_path_buf()));
        }
        return Ok(Some(libsystem::install(
            target,
            explicit,
            LibsystemOrigin::Explicit,
        )?));
    }
    if let Some((src, origin)) = libsystem::discover(None) {
        return Ok(Some(libsystem::install(target, &src, origin)?));
    }

    // crates.io / cargo install: freestanding dylib is vendored in this crate.
    if !EMBEDDED_LIBSYSTEM.is_empty() {
        return Ok(Some(libsystem::install_bytes(
            target,
            EMBEDDED_LIBSYSTEM,
            LibsystemOrigin::Embedded,
        )?));
    }

    Ok(None)
}

fn install_xcrun_for_create(target: &Path) -> Result<Option<XcrunInstall>, BottleError> {
    if let Some((src, origin)) = xcrun_tool::discover(None) {
        return Ok(Some(xcrun_tool::install(target, &src, origin)?));
    }
    if !EMBEDDED_XCRUN.is_empty() {
        return Ok(Some(xcrun_tool::install_bytes(
            target,
            EMBEDDED_XCRUN,
            XcrunOrigin::Embedded,
        )?));
    }
    Ok(None)
}

/// Destroys the registered bottle after `confirmed` is true.
///
/// When `confirmed` is false, returns [`BottleError::NotConfirmed`] without
/// touching the filesystem (CLI prompts, then retries with `true`).
pub fn destroy(confirmed: bool) -> Result<PathBuf, BottleError> {
    let Some(path) = registry::read_active()? else {
        return Err(BottleError::NotRegistered);
    };

    if !confirmed {
        return Err(BottleError::NotConfirmed);
    }

    if path.exists() {
        if layout::is_bottle_root(&path) {
            layout::remove_tree(&path)?;
        } else if path.is_dir() {
            // Registry path exists but marker missing — refuse blind rm -rf.
            return Err(BottleError::NotABottle(path));
        }
        // If path is a leftover file or already gone after check, still clear.
    }

    registry::clear_active()?;
    Ok(path)
}

/// Returns status of the registered bottle, if any.
pub fn status() -> Result<Option<BottleStatus>, BottleError> {
    let Some(path) = registry::read_active()? else {
        return Ok(None);
    };
    let exists = path.exists();
    let valid_marker = exists && layout::is_bottle_root(&path);
    let libsystem = exists && path.join(libsystem::GUEST_LIBSYSTEM_REL).is_file();
    let libcxx_alias = exists && layout::has_libcxx_symlink(&path);
    let libcurl_alias = exists && layout::has_libcurl_symlink(&path);
    Ok(Some(BottleStatus {
        path,
        exists,
        valid_marker,
        libsystem,
        libcxx_alias,
        libcurl_alias,
    }))
}

/// Returns the active bottle path when registered and valid on disk.
///
/// Used by CLI root resolution as a fallback after `--root` / `KAKEHASHI_ROOT`.
pub fn active_root() -> Result<Option<PathBuf>, BottleError> {
    match status()? {
        Some(s) if s.exists && s.valid_marker => Ok(Some(s.path)),
        _ => Ok(None),
    }
}

/// Idempotent bottle setup: create when missing, refresh libSystem when present.
///
/// ```text
/// # After cargo install kakehashi (uses embedded freestanding libSystem):
/// kh bottle ensure
///
/// # Dev: override with a just-built / staged dylib
/// kh bottle ensure --libsystem crates/kh-runtime/resources/libSystem.B.dylib
/// ```
///
/// * Valid registered bottle → reinstalls libSystem (unless `skip_libsystem`).
/// * Unregistered path that already has a bottle marker → adopt + refresh.
/// * Otherwise → same as [`create_with`].
/// * Explicit `--libsystem` that is missing is always an error.
pub fn ensure(opts: &CreateOptions<'_>) -> Result<CreateResult, BottleError> {
    if let Some(path) = active_root()? {
        return refresh_bottle(&path, opts);
    }

    // Adopt a marker'd bottle that is not in the registry (e.g. after wiping
    // KAKEHASHI_CONFIG_DIR but keeping the tree, or a previous manual path).
    if let Some(p) = opts.path {
        let abs = absolute(p)?;
        if layout::is_bottle_root(&abs) {
            return refresh_bottle(&abs, opts);
        }
    } else if let Ok(def) = registry::default_bottle_path()
        && layout::is_bottle_root(&def)
    {
        return refresh_bottle(&def, opts);
    }

    create_with(opts)
}

fn refresh_bottle(path: &Path, opts: &CreateOptions<'_>) -> Result<CreateResult, BottleError> {
    layout::ensure_libcxx_symlink(path)?;
    layout::ensure_libcurl_symlink(path)?;
    layout::ensure_libxar_symlink(path)?;
    layout::ensure_libz_symlink(path)?;
    layout::ensure_dev_nodes(path)?;
    layout::ensure_host_ssh_bridge(path)?;
    layout::ensure_host_bin_bridges(path)?;
    let libsystem = install_libsystem_for_create(path, opts)?;
    let xcrun = install_xcrun_for_create(path)?;
    // Mozilla / host CA bundle for OpenSSL CAfile + SecTrust host verify.
    if let Err(e) = super::ca_bundle::ensure_ca_bundle(path) {
        tracing::warn!(error = %e, "failed to seed bottle CA bundle");
    }
    registry::write_active(path)?;
    Ok(CreateResult {
        path: path.to_path_buf(),
        libsystem,
        xcrun,
    })
}

fn absolute(path: &Path) -> Result<PathBuf, BottleError> {
    if path.is_absolute() {
        return Ok(path.to_path_buf());
    }
    let cwd = std::env::current_dir()?;
    Ok(cwd.join(path))
}

#[cfg(test)]
#[allow(clippy::expect_used, clippy::panic, unsafe_code)]
mod tests {
    use super::*;
    use crate::bottle::registry::test_env_lock;
    use std::sync::atomic::{AtomicU64, Ordering};

    fn unique(prefix: &str) -> PathBuf {
        static N: AtomicU64 = AtomicU64::new(0);
        let n = N.fetch_add(1, Ordering::Relaxed);
        std::env::temp_dir().join(format!("kh-manage-{}-{}-{n}", prefix, std::process::id()))
    }

    struct EnvGuard {
        cfg: PathBuf,
        data: PathBuf,
    }

    impl EnvGuard {
        fn new() -> Self {
            let cfg = unique("cfg");
            let data = unique("data");
            drop(std::fs::remove_dir_all(&cfg));
            drop(std::fs::remove_dir_all(&data));
            std::fs::create_dir_all(&cfg).expect("cfg");
            std::fs::create_dir_all(&data).expect("data");
            // SAFETY: serialized by test_env_lock; EnvGuard restores on drop.
            unsafe {
                std::env::set_var("KAKEHASHI_CONFIG_DIR", &cfg);
                std::env::set_var("KAKEHASHI_DATA_DIR", &data);
            }
            Self { cfg, data }
        }
    }

    impl Drop for EnvGuard {
        fn drop(&mut self) {
            // SAFETY: paired with set_var in new(); still under test_env_lock.
            unsafe {
                std::env::remove_var("KAKEHASHI_CONFIG_DIR");
                std::env::remove_var("KAKEHASHI_DATA_DIR");
            }
            drop(std::fs::remove_dir_all(&self.cfg));
            drop(std::fs::remove_dir_all(&self.data));
        }
    }

    #[test]
    fn create_default_then_second_fails() {
        let _lock = test_env_lock();
        let g = EnvGuard::new();

        let created = create_with(&CreateOptions {
            skip_libsystem: true,
            ..CreateOptions::default()
        })
        .expect("create");
        let path = created.path;
        assert!(layout::is_bottle_root(&path));
        assert_eq!(path, g.data.join("bottle"));
        assert!(path.join("Volumes/linux").is_symlink());
        assert!(created.libsystem.is_none());

        let err = create(None).expect_err("second create");
        assert!(matches!(err, BottleError::AlreadyExists { .. }));

        let destroyed = destroy(true).expect("destroy");
        assert_eq!(destroyed, path);
        assert!(!path.exists());
        assert!(status().expect("status").is_none());
    }

    #[test]
    fn create_custom_path_and_rename_survives_registry_update() {
        let _lock = test_env_lock();
        let _g = EnvGuard::new();

        let custom = unique("custom-bottle-name");
        let created = create_with(&CreateOptions {
            path: Some(&custom),
            skip_libsystem: true,
            ..CreateOptions::default()
        })
        .expect("create custom");
        let path = created.path;
        assert_eq!(path, custom);
        assert!(layout::is_bottle_root(&path));

        // User renames the bottle directory — registry still points at old path.
        let renamed = unique("renamed-by-user");
        std::fs::rename(&path, &renamed).expect("rename");
        // Stale: exists=false after rename of registered path.
        let st = status().expect("status").expect("some");
        assert!(!st.exists);

        // Create should clear stale and succeed at a new path.
        let again = unique("after-rename");
        let path2 = create_with(&CreateOptions {
            path: Some(&again),
            skip_libsystem: true,
            ..CreateOptions::default()
        })
        .expect("create after stale");
        assert!(layout::is_bottle_root(&path2.path));

        destroy(true).expect("destroy");
        drop(std::fs::remove_dir_all(&renamed));
    }

    #[test]
    fn destroy_requires_confirmation() {
        let _lock = test_env_lock();
        let _g = EnvGuard::new();

        let path = create_with(&CreateOptions {
            skip_libsystem: true,
            ..CreateOptions::default()
        })
        .expect("create")
        .path;
        let err = destroy(false).expect_err("need confirm");
        assert!(matches!(err, BottleError::NotConfirmed));
        assert!(path.exists());
        destroy(true).expect("destroy");
    }

    #[test]
    fn volumes_linux_rw_outside_bottle() {
        let _lock = test_env_lock();
        let _g = EnvGuard::new();

        let root = create_with(&CreateOptions {
            skip_libsystem: true,
            ..CreateOptions::default()
        })
        .expect("create")
        .path;
        let token = format!("kh-manage-vol-{}", std::process::id());
        let host_file = std::env::temp_dir().join(&token);
        let payload = b"rw-outside\n";
        std::fs::write(&host_file, payload).expect("host write");

        let via = root
            .join(layout::VOLUMES_LINUX)
            .join(host_file.strip_prefix("/").expect("abs"));
        assert_eq!(std::fs::read(&via).expect("via read"), payload);

        let payload2 = b"from-bottle-side\n";
        std::fs::write(&via, payload2).expect("via write");
        assert_eq!(std::fs::read(&host_file).expect("host read"), payload2);

        drop(std::fs::remove_file(&host_file));
        destroy(true).expect("destroy");
    }

    #[test]
    fn create_installs_explicit_libsystem() {
        let _lock = test_env_lock();
        let _g = EnvGuard::new();

        // Staged freestanding guest dylib (crate resources/).
        let libsystem = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
            .join("resources/libSystem.B.dylib");
        assert!(
            libsystem.is_file(),
            "missing {}",
            libsystem.display()
        );

        let created = create_with(&CreateOptions {
            libsystem: Some(&libsystem),
            ..CreateOptions::default()
        })
        .expect("create with libsystem");
        assert!(created.libsystem.is_some());
        let dest = created.path.join(libsystem::GUEST_LIBSYSTEM_REL);
        assert!(dest.is_file());
        let st = status().expect("status").expect("registered");
        assert!(st.libsystem);
        assert!(st.libcxx_alias);
        assert!(st.libcurl_alias);
        assert!(layout::has_libcxx_symlink(&created.path));
        assert!(layout::has_libcurl_symlink(&created.path));

        destroy(true).expect("destroy");
    }

    #[test]
    fn ensure_creates_then_refreshes_libsystem() {
        let _lock = test_env_lock();
        let _g = EnvGuard::new();

        let libsystem = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
            .join("resources/libSystem.B.dylib");
        assert!(libsystem.is_file());

        let first = ensure(&CreateOptions {
            libsystem: Some(&libsystem),
            ..CreateOptions::default()
        })
        .expect("ensure create");
        assert!(first.libsystem.is_some());
        let dest = first.path.join(libsystem::GUEST_LIBSYSTEM_REL);
        let before = std::fs::metadata(&dest).expect("meta").len();

        // Second ensure reuses the same bottle and reinstalls the dylib.
        let second = ensure(&CreateOptions {
            libsystem: Some(&libsystem),
            ..CreateOptions::default()
        })
        .expect("ensure refresh");
        assert_eq!(second.path, first.path);
        assert!(second.libsystem.is_some());
        assert!(dest.is_file());
        let after = std::fs::metadata(&dest).expect("meta2").len();
        assert_eq!(before, after);

        destroy(true).expect("destroy");
    }
}