arcbox-hypervisor 0.4.9

Cross-platform hypervisor abstraction layer for ArcBox
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
//! Boot a Linux VM using Virtualization.framework
//!
//! Usage:
//! 1. Build: cargo build --bin arcbox-boot -p arcbox-hypervisor
//! 2. Sign: codesign --entitlements bundle/arcbox.entitlements --force -s - target/debug/arcbox-boot
//! 3. Run: arcbox-boot <kernel_path> [initrd_path] [options]

use clap::Parser;
use std::path::PathBuf;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::Duration;

/// Boot a Linux VM using Virtualization.framework
#[derive(Parser, Debug)]
#[command(name = "arcbox-boot")]
#[command(about = "Boot a Linux VM using ArcBox hypervisor")]
#[command(version)]
struct Args {
    /// Path to the Linux kernel image
    #[arg(value_name = "KERNEL")]
    kernel: PathBuf,

    /// Path to the initrd/initramfs image
    #[arg(value_name = "INITRD")]
    initrd: Option<PathBuf>,

    /// Attach a block device
    #[arg(long, value_name = "PATH")]
    disk: Option<PathBuf>,

    /// Enable NAT networking
    #[arg(long)]
    net: bool,

    /// Enable vsock device
    #[arg(long)]
    vsock: bool,

    /// Enable VirtioFS sharing (path to share)
    #[arg(long, value_name = "PATH")]
    virtiofs: Option<PathBuf>,

    /// Custom kernel command line
    #[arg(long, value_name = "CMDLINE")]
    cmdline: Option<String>,

    /// Number of vCPUs
    #[arg(long, default_value = "2")]
    vcpus: u32,

    /// Memory size in MB
    #[arg(long, default_value = "512")]
    memory: u64,

    /// Interactive mode - attach to serial console
    #[arg(short, long)]
    interactive: bool,
}

#[tokio::main]
async fn main() {
    let args = Args::parse();

    // Initialize tracing (only if not interactive)
    if !args.interactive {
        tracing_subscriber::fmt()
            .with_max_level(tracing::Level::DEBUG)
            .init();
    }

    println!("=== ArcBox VM Boot ===");
    println!();

    #[cfg(target_os = "macos")]
    run_macos(args);

    #[cfg(not(target_os = "macos"))]
    {
        let _ = args;
        eprintln!("This binary only works on macOS");
        std::process::exit(1);
    }
}

#[cfg(target_os = "macos")]
fn run_macos(args: Args) {
    use arcbox_hypervisor::{
        config::VmConfig,
        darwin::{DarwinHypervisor, DarwinVm, is_supported},
        traits::{Hypervisor, VirtualMachine},
        types::{CpuArch, VirtioDeviceConfig},
    };

    // Check support
    if !is_supported() {
        eprintln!("Error: Virtualization.framework not supported on this system");
        std::process::exit(1);
    }

    // Create hypervisor
    let hypervisor = DarwinHypervisor::new().expect("Failed to create hypervisor");
    let caps = hypervisor.capabilities();

    println!("Hypervisor capabilities:");
    println!("  Max vCPUs: {}", caps.max_vcpus);
    println!(
        "  Max memory: {} GB",
        caps.max_memory / (1024 * 1024 * 1024)
    );
    println!("  Rosetta: {}", caps.rosetta);
    println!();

    // Create VM config
    let cmdline = args
        .cmdline
        .clone()
        .unwrap_or_else(|| "console=hvc0 loglevel=8 root=/dev/ram0 rdinit=/init".to_string());
    let memory_bytes = args.memory * 1024 * 1024;

    let config = VmConfig {
        vcpu_count: args.vcpus,
        memory_size: memory_bytes,
        arch: CpuArch::native(),
        kernel_path: Some(args.kernel.to_string_lossy().into_owned()),
        kernel_cmdline: Some(cmdline.clone()),
        initrd_path: args
            .initrd
            .as_ref()
            .map(|p| p.to_string_lossy().into_owned()),
        ..Default::default()
    };

    println!("VM Configuration:");
    println!("  Kernel: {}", args.kernel.display());
    if let Some(ref initrd) = args.initrd {
        println!("  Initrd: {}", initrd.display());
    }
    if let Some(ref disk) = args.disk {
        println!("  Disk: {}", disk.display());
    }
    println!(
        "  Network: {}",
        if args.net {
            "enabled (NAT)"
        } else {
            "disabled"
        }
    );
    println!(
        "  Vsock: {}",
        if args.vsock { "enabled" } else { "disabled" }
    );
    if let Some(ref fs_path) = args.virtiofs {
        println!("  VirtioFS: {} -> arcbox", fs_path.display());
    } else {
        println!("  VirtioFS: disabled");
    }
    println!("  vCPUs: {}", config.vcpu_count);
    println!("  Memory: {} MB", args.memory);
    println!("  Cmdline: {:?}", cmdline);
    println!("  Interactive: {}", args.interactive);
    println!();

    // Create VM
    println!("Creating VM...");
    let mut vm: DarwinVm = hypervisor.create_vm(config).expect("Failed to create VM");
    println!("VM created: ID={}", vm.id());

    // Add block device if specified
    if let Some(ref disk) = args.disk {
        println!("Adding block device: {}", disk.display());
        let block_config = VirtioDeviceConfig::block(disk.to_string_lossy().into_owned(), false);
        match vm.add_virtio_device(block_config) {
            Ok(()) => println!("Block device added successfully"),
            Err(e) => eprintln!("Warning: Failed to add block device: {}", e),
        }
    }

    // Add network device if requested
    if args.net {
        println!("Adding network device (NAT)...");
        let net_config = VirtioDeviceConfig::network();
        match vm.add_virtio_device(net_config) {
            Ok(()) => println!("Network device added successfully"),
            Err(e) => eprintln!("Warning: Failed to add network device: {}", e),
        }
    }

    // Add vsock device if requested
    if args.vsock {
        println!("Adding vsock device...");
        let vsock_config = VirtioDeviceConfig::vsock();
        match vm.add_virtio_device(vsock_config) {
            Ok(()) => println!("Vsock device added successfully"),
            Err(e) => eprintln!("Warning: Failed to add vsock device: {}", e),
        }
    }

    // Add VirtioFS device if requested
    if let Some(ref fs_path) = args.virtiofs {
        println!("Adding VirtioFS device: {} -> arcbox", fs_path.display());
        let fs_config =
            VirtioDeviceConfig::filesystem(fs_path.to_string_lossy().into_owned(), "arcbox", false);
        match vm.add_virtio_device(fs_config) {
            Ok(()) => println!("VirtioFS device added successfully"),
            Err(e) => eprintln!("Warning: Failed to add VirtioFS device: {}", e),
        }
    }

    // Set up serial console
    println!("Setting up serial console...");
    match vm.setup_serial_console() {
        Ok(slave_path) => println!("Serial console available at: {}", slave_path),
        Err(e) => eprintln!("Warning: Failed to setup serial console: {}", e),
    }

    println!("Starting VM...");
    match vm.start() {
        Ok(()) => {
            println!("VM started successfully!");
            println!();

            if args.interactive {
                run_interactive_console(&mut vm);
            } else {
                run_demo_mode(&mut vm, args.vsock);
            }
        }
        Err(e) => {
            eprintln!("Failed to start VM: {}", e);
            eprintln!();
            eprintln!("Common issues:");
            eprintln!("  1. Binary not signed with com.apple.security.virtualization entitlement");
            eprintln!("  2. Kernel format not compatible (needs uncompressed ARM64 Image)");
            eprintln!("  3. Insufficient memory or CPU count");
            std::process::exit(1);
        }
    }
}

#[cfg(target_os = "macos")]
fn run_interactive_console(vm: &mut arcbox_hypervisor::darwin::DarwinVm) {
    use arcbox_hypervisor::traits::VirtualMachine;
    use std::io::{Read, Write};

    println!("Entering interactive console mode...");
    println!("Press Ctrl+A then X to exit.");
    println!();

    // Set up terminal raw mode
    let original_termios = setup_raw_mode();

    // Flag for clean shutdown
    let running = Arc::new(AtomicBool::new(true));
    let running_clone = running.clone();

    // Handle Ctrl+C
    ctrlc::set_handler(move || {
        running_clone.store(false, Ordering::SeqCst);
    })
    .expect("Failed to set Ctrl+C handler");

    let mut ctrl_a_pressed = false;
    let mut stdin = std::io::stdin();
    let mut input_buf = [0u8; 64];

    while running.load(Ordering::SeqCst) && vm.is_running() {
        // Check for console output (non-blocking)
        if let Ok(output) = vm.read_console_output() {
            if !output.is_empty() {
                print!("{}", output);
                let _ = std::io::stdout().flush();
            }
        }

        // Check for stdin input using poll
        let mut pollfd = libc::pollfd {
            fd: 0, // stdin
            events: libc::POLLIN,
            revents: 0,
        };

        let poll_result = unsafe { libc::poll(&raw mut pollfd, 1, 10) }; // 10ms timeout

        if poll_result > 0 && (pollfd.revents & libc::POLLIN) != 0 {
            match stdin.read(&mut input_buf) {
                Ok(0) => break, // EOF
                Ok(n) => {
                    for &byte in &input_buf[..n] {
                        if ctrl_a_pressed {
                            ctrl_a_pressed = false;
                            if byte == b'x' || byte == b'X' {
                                // Ctrl+A X = exit
                                println!("\r\n[Exiting console...]");
                                running.store(false, Ordering::SeqCst);
                                break;
                            } else if byte == 0x01 {
                                // Ctrl+A Ctrl+A = send Ctrl+A
                                let _ = vm.write_console_input("\x01");
                            } else {
                                // Unknown sequence, send both
                                let _ = vm.write_console_input("\x01");
                                let buf = [byte];
                                let s = String::from_utf8_lossy(&buf);
                                let _ = vm.write_console_input(&s);
                            }
                        } else if byte == 0x01 {
                            // Ctrl+A
                            ctrl_a_pressed = true;
                        } else {
                            let buf = [byte];
                            let s = String::from_utf8_lossy(&buf);
                            let _ = vm.write_console_input(&s);
                        }
                    }
                }
                Err(_) => {}
            }
        }
    }

    // Restore terminal
    restore_terminal(original_termios);

    println!();
    println!("Stopping VM...");
    match vm.stop() {
        Ok(()) => println!("VM stopped successfully"),
        Err(e) => println!("Error stopping VM: {}", e),
    }
}

#[cfg(target_os = "macos")]
fn run_demo_mode(vm: &mut arcbox_hypervisor::darwin::DarwinVm, test_vsock: bool) {
    use arcbox_hypervisor::traits::VirtualMachine;

    println!("VM is running. Press Ctrl+C to stop.");
    println!();

    // Run for a while, reading console output
    println!("Reading console output...");
    for i in 0..30 {
        std::thread::sleep(Duration::from_millis(500));

        // Read and print console output
        match vm.read_console_output() {
            Ok(output) => {
                if !output.is_empty() {
                    print!("{}", output);
                }
            }
            Err(e) => {
                println!("[console read error: {}]", e);
            }
        }

        if i % 2 == 1 {
            println!(
                "[{}s] VM state: {:?}, running: {}",
                (i + 1) / 2,
                vm.state(),
                vm.is_running()
            );
        }
    }

    // Test vsock connection if enabled
    if test_vsock {
        println!();
        for port in [2222u32, 1024] {
            println!("Testing vsock connection to port {}...", port);
            match vm.connect_vsock(port) {
                Ok(fd) => {
                    println!("  Vsock port {} connected! fd={}", port, fd);
                    unsafe { libc::close(fd) };
                    break;
                }
                Err(e) => {
                    println!("  Vsock port {} failed: {}", port, e);
                }
            }
        }
    }

    println!();
    println!("Stopping VM...");
    match vm.stop() {
        Ok(()) => println!("VM stopped successfully"),
        Err(e) => println!("Error stopping VM: {}", e),
    }
}

#[cfg(target_os = "macos")]
fn setup_raw_mode() -> libc::termios {
    use std::mem::MaybeUninit;

    let mut original: MaybeUninit<libc::termios> = MaybeUninit::uninit();

    unsafe {
        libc::tcgetattr(0, original.as_mut_ptr());
        let original = original.assume_init();

        let mut raw = original;
        // Disable canonical mode and echo
        raw.c_lflag &= !(libc::ICANON | libc::ECHO | libc::ISIG);
        // Disable input processing
        raw.c_iflag &= !(libc::IXON | libc::ICRNL);
        // Set minimum characters and timeout
        raw.c_cc[libc::VMIN] = 0;
        raw.c_cc[libc::VTIME] = 0;

        libc::tcsetattr(0, libc::TCSANOW, &raw const raw);

        original
    }
}

#[cfg(target_os = "macos")]
fn restore_terminal(original: libc::termios) {
    unsafe {
        libc::tcsetattr(0, libc::TCSANOW, &raw const original);
    }
}