vmsh 0.1.0

Transparently run a shell (or other binary) in a VM.
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
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
//! Transparently run a shell (or other binary) in a VM.

mod args;
mod embed;

#[expect(dead_code)]
#[path = "../init/init.rs"]
mod ignore_only_used_for_linting;

use std::cell::LazyCell;
use std::collections::BTreeMap;
use std::collections::HashMap;
use std::env;
use std::env::home_dir;
use std::env::temp_dir;
use std::ffi::CStr;
use std::ffi::CString;
use std::ffi::OsStr;
use std::ffi::OsString;
use std::ffi::c_char;
use std::fs;
use std::fs::File;
use std::fs::remove_file;
use std::io;
use std::io::Seek as _;
use std::io::Write as _;
use std::mem::MaybeUninit;
use std::ops::Deref;
use std::os::unix::ffi::OsStrExt as _;
use std::os::unix::ffi::OsStringExt as _;
use std::os::unix::fs::OpenOptionsExt as _;
use std::os::unix::io::AsRawFd as _;
use std::os::unix::io::FromRawFd as _;
use std::os::unix::io::OwnedFd;
use std::path::Path;
use std::path::PathBuf;
use std::process;
use std::ptr;

use anyhow::Context as _;
use anyhow::Result;
use anyhow::ensure;

use clap::Parser;

use vmsh::detect_kernel_format;
use vmsh::hostname;

use crate::args::Args;
use crate::args::Command;
use crate::args::RunArgs;


/// Embedded init binary.
const INIT_BINARY: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/vmsh-init"));

/// The virtiofs tag used by libkrun for the root filesystem device.
///
/// Corresponds to `KRUN_FS_ROOT_TAG` in `libkrun.h`.
const KRUN_FS_ROOT_TAG: &CStr = c"/dev/root";
// Use the same 512 MiB DAX window that `krun_set_root` uses.
const KRUN_FS_ROOT_SHM_SIZE: u64 = 1 << 29;


/// Compute the final list of filesystem shares and a flag indicating
/// whether the root filesystem should be mounted read-only or not.
///
/// Unless overwritten, the current directory as well as `/tmp/` will be
/// read-writable by default.
///
/// Returns the final list of share paths and whether the root should be
/// read-only (`false` only if `--share-rw /` was given).
fn compute_shares(cwd: &Path, mut share_rw: Vec<PathBuf>) -> (Vec<PathBuf>, bool) {
  // The root path is always handled via the root virtiofs device, so
  // remove it from the per-share list and derive the read-only flag
  // from the action.
  let root = Path::new("/");
  let mut root_ro = true;
  let () = share_rw.retain(|p| {
    let retain = p != root;
    if !retain {
      root_ro = false;
    }
    retain
  });

  // By default we mount at least cwd and `/tmp/` writable.
  let defaults = [cwd.to_path_buf(), temp_dir()];
  let () = share_rw.extend(defaults);

  (share_rw, root_ro)
}


/// Set up virtiofs devices for additional shares.
fn set_shares(ctx: u32, shares: &[PathBuf]) -> Result<()> {
  for (idx, path) in shares.iter().enumerate() {
    let tag = format!("vmsh-{idx}\0");
    // SANITY: We statically ensured a single terminating NUL byte is
    //         present.
    let c_tag = CString::from_vec_with_nul(tag.into_bytes()).unwrap();
    let c_path = CString::new(path.as_os_str().as_bytes())
      .with_context(|| format!("path `{}` contains NUL bytes", path.display()))?;
    let read_only = false;
    // SAFETY: `ctx` is a valid krun context, `c_tag` and `c_path` are
    //         valid NUL-terminated strings.
    let rc =
      unsafe { krun::krun_add_virtiofs3(ctx, c_tag.as_ptr(), c_path.as_ptr(), 0, read_only) };
    ensure!(
      rc >= 0,
      "failed to add virtiofs device for `{}`",
      path.display()
    );
  }

  Ok(())
}


/// Format share metadata as an environment variable value, to be passed
/// to the init process to be mounted accordingly.
///
/// Format: `tag:path:mode[;tag:path:mode]...`
/// where mode is `rw` or `ro`.
fn format_shares_env(shares: &[PathBuf]) -> Vec<u8> {
  let mut out = Vec::new();
  for (idx, path) in shares.iter().enumerate() {
    if !out.is_empty() {
      let () = out.push(b';');
    }
    let () = out.extend_from_slice(format!("vmsh-{idx}").as_bytes());
    let () = out.push(b':');
    let () = out.extend_from_slice(path.as_os_str().as_bytes());
  }
  out
}


/// RAII guard to clean up a temporary file on exit.
struct CleanupGuard(Option<PathBuf>);

impl Deref for CleanupGuard {
  type Target = Path;

  fn deref(&self) -> &Self::Target {
    // SANITY: We only ever unset `0` as part of the `Drop` impl.
    self.0.as_deref().unwrap()
  }
}

impl Drop for CleanupGuard {
  fn drop(&mut self) {
    if let Some(path) = self.0.take() {
      let _result = remove_file(path);
    }
  }
}


/// Write the embedded init binary to the host filesystem (visible in
/// guest via `virtiofs`).
fn deploy_init_binary(path: &Path) -> Result<CleanupGuard> {
  let mut file = fs::OpenOptions::new()
    .create_new(true)
    .mode(0o755)
    .write(true)
    .open(path)
    .with_context(|| format!("failed to create `{}`", path.display()))?;
  let guard = CleanupGuard(Some(path.to_path_buf()));

  let () = file
    .write_all(INIT_BINARY)
    .with_context(|| format!("failed to write init binary to {}", path.display()))?;

  Ok(guard)
}


/// Place the process in a private user namespace mapping the host
/// uid/gid to 0/0.
///
/// libkrun's virtiofs reads file metadata via the kernel's normal stat
/// path; once we're inside this namespace, file ownership is translated
/// transparently. Files owned by the invoking user appear as uid/gid 0
/// (root in the guest); files owned by other host ids appear as the
/// overflow id (65534, nobody) -- still readable when world-readable.
///
/// Writes from the guest happen as guest uid 0; the kernel translates
/// that back to the host uid via the same mapping, so guest-created
/// files end up host-owned by the invoking user.
fn enter_user_namespace() -> Result<()> {
  // Capture uid/gid BEFORE `unshare`. Afterwards, `getuid`/`getgid`
  // return the overflow id (65534) until the maps are written.
  // SAFETY: `getuid` is always safe to call.
  let uid = unsafe { libc::getuid() };
  // SAFETY: `getgid` is always safe to call.
  let gid = unsafe { libc::getgid() };

  // SAFETY: `unshare` is always safe to call.
  let rc = unsafe { libc::unshare(libc::CLONE_NEWUSER) };
  if rc != 0 {
    return Err(io::Error::last_os_error()).context("failed to enter new user namespace")
  }

  let write_proc = |path: &str, content: &str| -> Result<()> {
    // The `proc` map files reject `O_TRUNC`, so `fs::write` is not
    // usable here; open without truncate.
    let mut file = fs::OpenOptions::new()
      .write(true)
      .open(path)
      .with_context(|| format!("failed to open `{path}`"))?;
    let () = file
      .write_all(content.as_bytes())
      .with_context(|| format!("failed to write `{path}`"))?;
    Ok(())
  };

  // `setgroups=deny` is required before writing `gid_map` for an
  // unprivileged self-write.
  let () = write_proc("/proc/self/setgroups", "deny\n")?;
  let () = write_proc("/proc/self/uid_map", &format!("0 {uid} 1\n"))?;
  let () = write_proc("/proc/self/gid_map", &format!("0 {gid} 1\n"))?;

  Ok(())
}


/// Build the environment variable payload from CLI flags and host env.
///
/// Variables that are reserved or overridden by vmsh (`VMSH_*`) or
/// internal to libkrun (`KRUN_*`) are excluded when `all_envs` is set.
fn build_env_content(
  env_args: &[String],
  all_envs: bool,
  host_env: impl IntoIterator<Item = (OsString, OsString)>,
) -> Vec<u8> {
  let host = LazyCell::new(|| host_env.into_iter().collect::<HashMap<_, _>>());
  let mut out = BTreeMap::new();

  if all_envs {
    for (key, value) in &*host {
      if let Some(k) = key.to_str() {
        if k.starts_with("VMSH_") || k.starts_with("KRUN_") {
          continue;
        }
      }
      let _prev = out.insert(key.as_os_str(), value.as_os_str());
    }
  }

  for arg in env_args {
    if let Some(pos) = arg.find('=') {
      let key = OsStr::new(&arg[..pos]);
      let value = OsStr::new(&arg[pos + 1..]);
      let _prev = out.insert(key, value);
    } else {
      let key = OsStr::new(arg);
      if let Some(value) = host.get(key) {
        let _prev = out.insert(key, value);
      }
    }
  }

  let mut buf = Vec::new();
  for (key, value) in &out {
    let () = buf.extend_from_slice(key.as_bytes());
    let () = buf.push(b'=');
    let () = buf.extend_from_slice(value.as_bytes());
    let () = buf.push(b'\n');
  }
  buf
}


/// Create a memfd containing the environment variable payload.
fn create_env_memfd(content: &[u8]) -> Result<OwnedFd> {
  // SAFETY: "vmsh-env" is a valid NUL-terminated name.
  let fd = unsafe { libc::memfd_create(c"vmsh-env".as_ptr(), 0) };
  ensure!(fd >= 0, "failed to create memfd for env vars");

  // SAFETY: `memfd_create` succeeded, so `fd` is a valid, open file
  //         descriptor that we own.
  let fd = unsafe { OwnedFd::from_raw_fd(fd) };
  let mut file = File::from(fd);
  let () = file
    .write_all(content)
    .context("failed to write env vars to memfd")?;
  let () = file.rewind().context("failed to seek memfd to start")?;

  Ok(file.into())
}


fn set_kernel(ctx: u32, kernel: PathBuf, init_guest_path: &Path, verbosity: u8) -> Result<()> {
  let kernel_format = detect_kernel_format(&kernel)?;
  let quiet = if verbosity < 2 { "quiet" } else { "" };
  let cmdline = format!(
    "earlycon=uart,io,0x3f8 reboot=k panic=5 console=hvc0 rootfstype=virtiofs rw init={} {quiet}",
    init_guest_path.display()
  );
  let c_kernel_path = CString::new(kernel.into_os_string().into_vec())?;
  // SANITY: `cmdline` is built from ASCII literals and a path display.
  let c_cmdline = CString::new(cmdline).unwrap();
  let initramfs = ptr::null();

  // SAFETY: `ctx` is a valid krun context and all pointers reference
  //         valid NUL-terminated strings (or null for initramfs).
  let rc = unsafe {
    krun::krun_set_kernel(
      ctx,
      c_kernel_path.as_ptr(),
      kernel_format as u32,
      initramfs,
      c_cmdline.as_ptr(),
    )
  };
  ensure!(rc >= 0, "failed to set kernel (code {rc})");
  Ok(())
}


fn set_exec(
  ctx: u32,
  command: Vec<String>,
  has_env_port: bool,
  unlink_paths: &[&Path],
  shares_env: Option<&[u8]>,
) -> Result<()> {
  // Provide defaults for some relevant variables, but these will be
  // overwritten by any user provided values.
  let hostname = hostname().context("failed to retrieve host name")?;
  let hostname = CString::new(format!("HOSTNAME={hostname}")).unwrap();
  let home_owned;
  let home = if let Some(home_dir) = home_dir() {
    home_owned = CString::new(format!("HOME={}", home_dir.display())).unwrap();
    &home_owned
  } else {
    c"/root"
  };
  let cwd = env::current_dir()
    .and_then(|p| p.canonicalize())
    .context("failed to determine current directory")?;
  let cwd = CString::new(format!("WORKDIR={}", cwd.display())).unwrap();

  // Determine which of stdin/stdout/stderr are non-terminal.
  // `libkrun` creates virtio console ports for redirected FDs; tell the
  // guest init which ports to look for.
  // SAFETY: `isatty` is always safe to call.
  let stdin_redir = unsafe { libc::isatty(libc::STDIN_FILENO) == 0 };
  // SAFETY: `isatty` is always safe to call.
  let stdout_redir = unsafe { libc::isatty(libc::STDOUT_FILENO) == 0 };
  // SAFETY: `isatty` is always safe to call.
  let stderr_redir = unsafe { libc::isatty(libc::STDERR_FILENO) == 0 };

  let mut env_ptrs = vec![hostname.as_ptr(), home.as_ptr(), cwd.as_ptr()];

  // Tell the guest init which temporary files to unlink. libkrun exits
  // the process hard on VM exit, bypassing host-side RAII cleanup.
  let unlink_env = if !unlink_paths.is_empty() {
    let value = unlink_paths
      .iter()
      .map(|p| p.display().to_string())
      .collect::<Vec<_>>()
      .join(":");
    Some(CString::new(format!("VMSH_UNLINK={value}"))?)
  } else {
    None
  };
  if let Some(ref env) = unlink_env {
    let () = env_ptrs.push(env.as_ptr());
  }

  // Tell the guest init to look for a "krun-env" virtio console port.
  let env_port_env = c"VMSH_ENV_PORT=1";
  if has_env_port {
    let () = env_ptrs.push(env_port_env.as_ptr());
  }

  if stdin_redir {
    let () = env_ptrs.push(c"VMSH_STDIN=1".as_ptr());
  }
  if stdout_redir {
    let () = env_ptrs.push(c"VMSH_STDOUT=1".as_ptr());
  }
  if stderr_redir {
    let () = env_ptrs.push(c"VMSH_STDERR=1".as_ptr());
  }

  let shares_env_cstr;
  if let Some(val) = shares_env {
    let mut buf = b"VMSH_SHARES=".to_vec();
    let () = buf.extend_from_slice(val);
    shares_env_cstr = CString::new(buf)?;
    let () = env_ptrs.push(shares_env_cstr.as_ptr());
  }

  let () = env_ptrs.push(ptr::null());

  if !command.is_empty() {
    let cmd = CString::new(command[0].as_str())?;
    let args = command[1..]
      .iter()
      .map(|a| CString::new(a.as_str()))
      .collect::<Result<Vec<_>, _>>()?;
    let mut argv = args
      .iter()
      .map(|a| a.as_ptr())
      .collect::<Vec<*const c_char>>();
    let () = argv.push(ptr::null());

    // SAFETY: `ctx` is a valid krun context and all pointers reference
    //         valid NUL-terminated strings or null sentinels.
    let rc = unsafe { krun::krun_set_exec(ctx, cmd.as_ptr(), argv.as_ptr(), env_ptrs.as_ptr()) };
    ensure!(rc >= 0, "failed to set exec command");
  } else {
    // SAFETY: `ctx` is a valid krun context and `env_ptrs` is a valid
    //         NUL-terminated pointer array.
    let rc = unsafe { krun::krun_set_env(ctx, env_ptrs.as_ptr()) };
    ensure!(rc >= 0, "failed to set environment");
  }
  Ok(())
}


fn exec_vm(args: RunArgs, init_guest_path: &Path, unlink_paths: &[&Path]) -> Result<()> {
  let RunArgs {
    kernel,
    cpus,
    memory,
    net,
    uds,
    command,
    env_vars,
    all_envs,
    no_uid_map: _,
    verbosity,
    share_rw,
  } = args;

  // SANITY: Caller guarantees that a kernel is always set.
  let kernel = kernel.unwrap();

  if verbosity > 0 {
    // SAFETY: `STDERR_FILENO` is a valid file descriptor.
    let rc = unsafe {
      krun::krun_init_log(
        libc::STDERR_FILENO,
        u32::from(verbosity),
        2, // KRUN_LOG_STYLE_NEVER
        0, // use env
      )
    };
    ensure!(rc >= 0, "failed to set log level");
  }

  let ctx = krun::krun_create_ctx() as u32;

  let rc = krun::krun_set_vm_config(ctx, cpus, memory);
  ensure!(rc >= 0, "failed to set VM config");

  // libkrun creates an implicit virtio console on `hvc0` connected to
  // stdin/stdout/stderr, so we don't need to add one explicitly.

  // Add a serial console so `earlycon=uart,io,0x3f8` works.
  // SAFETY: `ctx` is a valid krun context.
  let rc = unsafe {
    krun::krun_add_serial_console_default(
      ctx,
      -1,
      if verbosity > 0 {
        libc::STDERR_FILENO
      } else {
        -1
      },
    )
  };
  ensure!(rc >= 0, "failed to add serial console");

  // Enable TSI (Transparent Socket Impersonation) for networking. TSI
  // intercepts AF_INET/AF_INET6 socket calls in the guest kernel and
  // proxies them through the host VMM via virtio-vsock, providing
  // network connectivity without a virtual NIC. This requires a guest
  // kernel with TSI patches applied (see `var/linux-tsi-patches/`).
  const KRUN_TSI_HIJACK_INET: u32 = 1 << 0;
  const KRUN_TSI_HIJACK_UNIX: u32 = 1 << 1;

  let rc = krun::krun_disable_implicit_vsock(ctx);
  ensure!(rc >= 0, "failed to disable implicit vsock");

  let mut tsi_features = 0;
  if net {
    tsi_features |= KRUN_TSI_HIJACK_INET;
  }
  if net || uds {
    tsi_features |= KRUN_TSI_HIJACK_UNIX;
  }
  let rc = krun::krun_add_vsock(ctx, tsi_features);
  ensure!(rc >= 0, "failed to add vsock device");

  let () = set_kernel(ctx, kernel, init_guest_path, verbosity)?;

  // Compute filesystem shares. By default, the root is read-only with
  // the cwd and `/tmp/` shared read-write. User flags override this.
  let cwd = env::current_dir()
    .and_then(|p| p.canonicalize())
    .context("failed to determine current directory")?;
  let (shares, root_ro) = compute_shares(&cwd, share_rw);
  let () = set_shares(ctx, &shares)?;

  let c_rootfs = c"/";
  // SAFETY: `ctx` is a valid krun context, `KRUN_FS_ROOT_TAG` and
  //         `c_rootfs` are valid NUL-terminated strings.
  let rc = unsafe {
    krun::krun_add_virtiofs3(
      ctx,
      KRUN_FS_ROOT_TAG.as_ptr(),
      c_rootfs.as_ptr(),
      KRUN_FS_ROOT_SHM_SIZE,
      root_ro,
    )
  };
  ensure!(rc >= 0, "failed to set root filesystem");

  // Pass environment variables to the guest via a virtio console port
  // backed by a memfd. The guest init discovers the port by name and
  // reads KEY=VALUE lines until EOF.
  let env_content = build_env_content(&env_vars, all_envs, env::vars_os());
  let has_env_port = !env_content.is_empty();
  let env_fd;
  if has_env_port {
    env_fd = create_env_memfd(&env_content)?;

    // SAFETY: `ctx` is a valid krun context.
    let console_id = unsafe { krun::krun_add_virtio_console_multiport(ctx) };
    ensure!(console_id >= 0, "failed to add virtio console for env port");

    // SAFETY: `ctx` is a valid krun context, `console_id` is a valid
    //         console index, "krun-env" is NUL-terminated, and `env_fd`
    //         is a valid, open file descriptor.
    let rc = unsafe {
      krun::krun_add_console_port_inout(
        ctx,
        console_id as u32,
        c"krun-env".as_ptr(),
        env_fd.as_raw_fd(),
        -1,
      )
    };
    ensure!(rc >= 0, "failed to add env console port");
  }

  // Build share metadata for the guest init.
  let shares_env_val = format_shares_env(&shares);
  let shares_env = if shares_env_val.is_empty() {
    None
  } else {
    Some(shares_env_val.as_slice())
  };

  let () = set_exec(ctx, command, has_env_port, unlink_paths, shares_env)?;

  let rc = krun::krun_start_enter(ctx);
  ensure!(rc >= 0, "failed to start VM (code {rc})");
  Ok(())
}


/// Raise `RLIMIT_NOFILE` to the maximum allowed number of file
/// descriptors.
///
/// This is necessary, because libkrun's virtiofs passthrough filesystem
/// holds one open file descriptor per inode the guest touches, which
/// can quickly add up.
fn set_rlimits() -> Result<()> {
  let mut limit = MaybeUninit::<libc::rlimit>::uninit();
  // SAFETY: `getrlimit` initializes the `rlimit` struct on success.
  let rc = unsafe { libc::getrlimit(libc::RLIMIT_NOFILE, limit.as_mut_ptr()) };
  ensure!(rc >= 0, "failed to get `RLIMIT_NOFILE`");

  // SAFETY: `getrlimit` succeeded, so `limit` is fully initialized.
  let mut limit = unsafe { limit.assume_init() };
  limit.rlim_cur = limit.rlim_max;
  // SAFETY: `limit` is a valid, initialized `rlimit` struct.
  let _rc = unsafe { libc::setrlimit(libc::RLIMIT_NOFILE, &limit) };
  Ok(())
}


fn main() -> Result<()> {
  let args = Args::parse();

  let mut args = match args.command {
    Some(Command::Embed(embed_args)) => {
      return embed::embed_kernel(&embed_args.kernel, embed_args.output.as_deref());
    },
    Some(Command::Run(run_args)) => run_args,
    None => args.args,
  };

  // Resolve kernel: explicit positional arg > embedded > error.
  let kernel_guard;
  let extracted_kernel = match &mut args.kernel {
    Some(path) => {
      ensure!(
        path.exists(),
        "failed to find kernel at `{}`",
        path.display()
      );
      None
    },
    None => {
      kernel_guard = embed::extract_embedded_kernel()
        .context("no kernel specified and no embedded kernel found")?;
      args.kernel = Some(kernel_guard.to_path_buf());
      Some(&*kernel_guard)
    },
  };

  let () = set_rlimits()?;

  // Deploy init binary to `/tmp/` which is typically writable and
  // visible inside the guest via virtiofs.
  let init_filename = format!("vmsh-init-{}", process::id());
  let init_path = temp_dir().join(&init_filename);
  let _guard = deploy_init_binary(&init_path)?;

  // Collect temporary files for the guest init to clean up.
  let mut unlink_paths = vec![init_path.as_path()];
  if let Some(kernel_path) = extracted_kernel {
    let () = unlink_paths.push(kernel_path);
  }

  if !args.no_uid_map {
    // Enter a private user namespace mapping the host uid/gid to 0/0.
    // Then the guest sees the invoking user's files as root-owned without
    // any host-side mount manipulation.
    let () = enter_user_namespace().map_err(|err| {
      if err
        .root_cause()
        .downcast_ref::<io::Error>()
        .map(|err| err.kind() == io::ErrorKind::PermissionDenied)
        .unwrap_or(false)
      {
        Result::<(), _>::Err(err)
          .context(
            "user namespace setup failed; check \
            `kernel.unprivileged_userns_clone` or \
            `kernel.apparmor_restrict_unprivileged_userns`, or rerun \
            with `--no-uid-map` to skip user-namespace setup",
          )
          .unwrap_err()
      } else {
        err
      }
    })?;
  }

  let () = exec_vm(args, &init_path, &unlink_paths)?;
  Ok(())
}


#[cfg(test)]
mod tests {
  use super::*;


  fn host_env() -> Vec<(OsString, OsString)> {
    vec![
      (OsString::from("PATH"), OsString::from("/usr/bin")),
      (OsString::from("USER"), OsString::from("alice")),
      (OsString::from("HOSTNAME"), OsString::from("myhost")),
      (OsString::from("HOME"), OsString::from("/home/alice")),
      (OsString::from("VMSH_REDIRECT"), OsString::from("3")),
      (
        OsString::from("VMSH_KERNEL"),
        OsString::from("/boot/vmlinuz"),
      ),
      (OsString::from("KRUN_LOG_LEVEL"), OsString::from("debug")),
      (OsString::from("EDITOR"), OsString::from("vim")),
    ]
  }


  /// Test that without environment variable related flags set,
  /// [`build_env_content`] produces an empty env var file.
  #[test]
  fn no_flags_empty_output() {
    let all_envs = false;
    let content = build_env_content(&[], all_envs, Vec::<(OsString, OsString)>::new());
    assert!(content.is_empty());
  }

  /// Check that `all_envs` exports non-blocked host vars.
  #[test]
  fn all_envs_exports_host() {
    let all_envs = true;
    let content = build_env_content(&[], all_envs, host_env());
    let text = String::from_utf8(content).unwrap();
    assert!(text.contains("PATH=/usr/bin\n"));
    assert!(text.contains("USER=alice\n"));
    assert!(text.contains("EDITOR=vim\n"));
  }

  /// Verify that `all_envs` excludes `VMSH_*` and `KRUN_*` prefixed
  /// variables.
  #[test]
  fn all_envs_skips_blocked() {
    let all_envs = true;
    let content = build_env_content(&[], all_envs, host_env());
    let text = String::from_utf8(content).unwrap();
    assert!(text.contains("HOSTNAME=myhost\n"));
    assert!(text.contains("HOME=/home/alice\n"));
    assert!(!text.contains("VMSH_REDIRECT="));
    assert!(!text.contains("VMSH_KERNEL="));
    assert!(!text.contains("KRUN_LOG_LEVEL="));
  }

  /// Test that `--env=KEY` resolves its value from the host
  /// environment.
  #[test]
  fn env_key_resolves_from_host() {
    let all_envs = false;
    let content = build_env_content(&["PATH".to_string()], all_envs, host_env());
    let text = String::from_utf8(content).unwrap();
    assert_eq!(text, "PATH=/usr/bin\n");
  }

  /// Check that `--env=KEY=VALUE` uses the provided value.
  #[test]
  fn env_key_value_explicit() {
    let all_envs = false;
    let content = build_env_content(
      &["FOO=bar".to_string()],
      all_envs,
      Vec::<(OsString, OsString)>::new(),
    );
    let text = String::from_utf8(content).unwrap();
    assert_eq!(text, "FOO=bar\n");
  }

  /// Verify that a bare key missing from the host env is silently
  /// skipped.
  #[test]
  fn env_key_missing_skipped() {
    let all_envs = false;
    let content = build_env_content(&["NONEXISTENT".to_string()], all_envs, host_env());
    assert!(content.is_empty());
  }

  /// Test that `--env=KEY=VALUE` overrides the same key from
  /// `all_envs`.
  #[test]
  fn env_overrides_all_envs() {
    let all_envs = true;
    let content = build_env_content(&["PATH=custom".to_string()], all_envs, host_env());
    let text = String::from_utf8(content).unwrap();
    assert!(text.contains("PATH=custom\n"));
    assert!(!text.contains("PATH=/usr/bin\n"));
  }

  /// Check that a key in both `all_envs` and `--env` produces only one
  /// entry.
  #[test]
  fn no_duplicates() {
    let all_envs = true;
    let content = build_env_content(&["PATH".to_string()], all_envs, host_env());
    let text = String::from_utf8(content).unwrap();
    let count = text.matches("PATH=").count();
    assert_eq!(count, 1);
  }

  /// Verify the `VMSH_SHARES` env var format.
  #[test]
  fn share_metadata_format() {
    let shares = [
      PathBuf::from("/home/user/project"),
      PathBuf::from("/tmp"),
      PathBuf::from("/opt"),
    ];
    let env = format_shares_env(&shares);
    assert_eq!(env, b"vmsh-0:/home/user/project;vmsh-1:/tmp;vmsh-2:/opt");
  }

  /// Check that non-UTF-8 path bytes survive the share encoding round-trip.
  #[test]
  fn non_utf8_paths() {
    // 0x80 is not valid UTF-8 on its own.
    let rw_path = PathBuf::from(OsString::from_vec(b"/rw-\x80".to_vec()));
    let env = format_shares_env(&[rw_path]);
    assert_eq!(env, b"vmsh-0:/rw-\x80");
  }
}