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
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
//! Virtual machine implementation for macOS.
//!
//! This module uses arcbox-vz for Virtualization.framework bindings.
use std::os::unix::io::RawFd;
use std::sync::{
RwLock,
atomic::{AtomicBool, AtomicU64, Ordering},
};
use std::time::Duration;
use arcbox_vz::{
EntropyDeviceConfiguration, GenericPlatform, LinuxBootLoader, LinuxRosettaDirectoryShare,
MemoryBalloonDeviceConfiguration, NetworkDeviceConfiguration, RosettaAvailability,
SerialPortConfiguration, SharedDirectory, SingleDirectoryShare, SocketDeviceConfiguration,
StorageDeviceConfiguration, VirtioFileSystemDeviceConfiguration, VirtualMachineConfiguration,
VirtualMachineState,
};
use crate::{
config::VmConfig,
error::HypervisorError,
traits::VirtualMachine,
types::{DeviceSnapshot, VirtioDeviceConfig, VirtioDeviceType},
};
use super::memory::DarwinMemory;
use super::vcpu::DarwinVcpu;
/// Global VM ID counter.
static VM_ID_COUNTER: AtomicU64 = AtomicU64::new(0);
/// Reserved vsock port for IRQ signaling.
///
/// This port is used by the host to send IRQ signals to the guest.
/// The guest arcbox-agent listens on this port and handles incoming IRQ signals.
const VSOCK_IRQ_SIGNAL_PORT: u32 = 1025;
/// Virtual machine state.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum VmState {
/// VM is created but not started.
Created,
/// VM is starting.
Starting,
/// VM is running.
Running,
/// VM is paused.
Paused,
/// VM is stopping.
Stopping,
/// VM is stopped.
Stopped,
/// VM encountered an error.
Error,
}
/// Virtual machine implementation for Darwin (macOS).
///
/// This wraps arcbox-vz types for Virtualization.framework and provides the
/// platform-agnostic interface.
pub struct DarwinVm {
/// Unique VM ID.
id: u64,
/// VM configuration.
config: VmConfig,
/// Guest memory.
memory: DarwinMemory,
/// Created vCPUs.
vcpus: RwLock<Vec<u32>>,
/// Current state.
state: RwLock<VmState>,
/// Whether the VM is running.
running: AtomicBool,
/// VZ configuration builder (consumed when VM is built).
vz_config: Option<VirtualMachineConfiguration>,
/// VZ virtual machine handle (created from configuration).
vz_vm: Option<arcbox_vz::VirtualMachine>,
/// Console serial port file descriptors (hvc0): kernel/init output.
console_fds: Option<(RawFd, RawFd)>,
/// Agent log serial port file descriptors (hvc1): dedicated agent tracing channel.
agent_log_fds: Option<(RawFd, RawFd)>,
/// Device configuration metadata for snapshots.
///
/// Since Virtualization.framework doesn't expose device state, we store
/// the original configuration to enable re-creation on restore.
device_configs: Vec<VirtioDeviceConfig>,
/// Vsock file descriptor for IRQ signaling (if established).
///
/// Since Darwin's Virtualization.framework doesn't expose direct IRQ injection,
/// we use vsock-based signaling as an alternative. The host sends IRQ signals
/// through this connection, and the guest agent handles them.
vsock_irq_fd: RwLock<Option<RawFd>>,
/// Whether a balloon device has been configured.
///
/// The balloon device configuration is stored here during VM setup
/// and added to the VZ configuration in `finalize_configuration()`.
balloon_configured: bool,
/// When true, `Drop` will skip calling `self.stop()`. Used when the
/// guest has already halted and the VF stop path would crash.
skip_stop_on_drop: bool,
}
// Safety: The VZ handles are properly synchronized and only accessed
// through controlled interfaces.
unsafe impl Send for DarwinVm {}
unsafe impl Sync for DarwinVm {}
impl DarwinVm {
/// Marks this VM to skip calling `stop()` when dropped.
///
/// Use when the guest has already halted (e.g. ACPI shutdown) and the
/// Virtualization.framework stop path would crash. FDs and other
/// resources are still released normally via Drop.
pub fn set_skip_stop_on_drop(&mut self) {
self.skip_stop_on_drop = true;
}
/// Creates a new Darwin VM.
pub(crate) fn new(config: VmConfig) -> Result<Self, HypervisorError> {
let id = VM_ID_COUNTER.fetch_add(1, Ordering::SeqCst);
// Allocate guest memory
let memory = DarwinMemory::new(config.memory_size)?;
// Create VZ configuration using arcbox-vz API
let mut vz_config = VirtualMachineConfiguration::new()
.map_err(|e| HypervisorError::VmCreationFailed(e.to_string()))?;
// Set CPU count and memory size
vz_config.set_cpu_count(config.vcpu_count as usize);
vz_config.set_memory_size(config.memory_size);
// Set up generic platform for Linux VMs on Apple Silicon
let platform = GenericPlatform::new().map_err(|e| {
HypervisorError::VmCreationFailed(format!("Failed to create platform: {e}"))
})?;
if GenericPlatform::is_nested_virt_supported() {
platform.set_nested_virt_enabled(true);
tracing::info!("Nested virtualization enabled");
}
vz_config.set_platform(platform);
tracing::debug!("Set generic platform configuration");
// Set up boot loader if kernel path is specified
if let Some(ref kernel_path) = config.kernel_path {
let mut boot_loader = LinuxBootLoader::new(kernel_path).map_err(|e| {
HypervisorError::VmCreationFailed(format!("Failed to create boot loader: {e}"))
})?;
tracing::debug!("Created boot loader for kernel: {}", kernel_path);
if let Some(ref cmdline) = config.kernel_cmdline {
boot_loader.set_command_line(cmdline);
tracing::debug!("Set kernel cmdline: {}", cmdline);
}
if let Some(ref initrd_path) = config.initrd_path {
boot_loader.set_initial_ramdisk(initrd_path);
tracing::debug!("Set initrd: {}", initrd_path);
}
vz_config.set_boot_loader(boot_loader);
tracing::debug!("Boot loader configured");
}
// Add entropy device for random number generation
let entropy = EntropyDeviceConfiguration::new().map_err(|e| {
HypervisorError::VmCreationFailed(format!("Failed to create entropy device: {e}"))
})?;
vz_config.add_entropy_device(entropy);
tracing::debug!("Entropy device configured");
// Note: We don't validate or create VM yet - devices may be added later
// The VM will be created in finalize_configuration()
tracing::info!(
"Created VM {}: vcpus={}, memory={}MB",
id,
config.vcpu_count,
config.memory_size / (1024 * 1024)
);
Ok(Self {
id,
config,
memory,
vcpus: RwLock::new(Vec::new()),
state: RwLock::new(VmState::Created),
running: AtomicBool::new(false),
vz_config: Some(vz_config),
vz_vm: None,
console_fds: None,
agent_log_fds: None,
device_configs: Vec::new(),
vsock_irq_fd: RwLock::new(None),
balloon_configured: false,
skip_stop_on_drop: false,
})
}
/// Configures dual serial console ports using pipes.
///
/// Creates two VirtIO console ports:
/// - Port 0 (`hvc0`): kernel/init console output
/// - Port 1 (`hvc1`): dedicated agent log channel
///
/// Returns "pipe" on success. Use `read_console_output()` and
/// `read_agent_log_output()` to read from each port.
pub fn setup_serial_console(&mut self) -> Result<String, HypervisorError> {
let make_port =
|label: &str| -> Result<(SerialPortConfiguration, RawFd, RawFd), HypervisorError> {
let port = SerialPortConfiguration::virtio_console()
.map_err(|e| HypervisorError::DeviceError(e.to_string()))?;
let read_fd = port.read_fd().ok_or_else(|| {
HypervisorError::DeviceError(format!("Failed to get {label} read fd"))
})?;
let write_fd = port.write_fd().ok_or_else(|| {
HypervisorError::DeviceError(format!("Failed to get {label} write fd"))
})?;
Ok((port, read_fd, write_fd))
};
// Port 0 (hvc0): kernel/init console
let (console_port, console_read, console_write) = make_port("console")?;
self.console_fds = Some((console_read, console_write));
tracing::info!(
"Console port (hvc0): read_fd={}, write_fd={}",
console_read,
console_write
);
// Port 1 (hvc1): agent log channel
let (agent_log_port, agent_read, agent_write) = make_port("agent-log")?;
self.agent_log_fds = Some((agent_read, agent_write));
tracing::info!(
"Agent log port (hvc1): read_fd={}, write_fd={}",
agent_read,
agent_write
);
// Add ports in order — array index determines hvc device number.
if let Some(ref mut vz_config) = self.vz_config {
vz_config.add_serial_port(console_port);
vz_config.add_serial_port(agent_log_port);
tracing::debug!("Dual serial ports configured (hvc0 + hvc1)");
}
Ok("pipe".to_string())
}
/// Finalizes configuration and creates the actual VZ VM.
fn finalize_configuration(&mut self) -> Result<(), HypervisorError> {
let mut vz_config = self
.vz_config
.take()
.ok_or_else(|| HypervisorError::VmCreationFailed("No VZ configuration".to_string()))?;
// NOTE: Storage, network, serial, and other devices have already been added
// via add_*_device methods during configuration phase.
// Add balloon device if configured.
if self.balloon_configured {
let balloon = MemoryBalloonDeviceConfiguration::new().map_err(|e| {
HypervisorError::DeviceError(format!(
"Failed to create balloon device configuration: {e}"
))
})?;
vz_config.add_memory_balloon_device(balloon);
tracing::debug!("Balloon device configured for VM {}", self.id);
}
// Build the VM. This validates configuration internally and creates
// the VZVirtualMachine instance with a dedicated dispatch queue.
let vz_vm = vz_config
.build()
.map_err(|e| HypervisorError::VmCreationFailed(format!("Failed to build VM: {e}")))?;
self.vz_vm = Some(vz_vm);
tracing::debug!("VM {} configuration finalized", self.id);
Ok(())
}
/// Waits for the VM to reach a specific state.
///
/// Uses progressive backoff: starts with short spins then yields, avoiding
/// the overhead of a fixed 100ms poll interval for fast transitions.
fn wait_for_state(
&self,
target: VirtualMachineState,
timeout: Duration,
) -> Result<(), HypervisorError> {
let start = std::time::Instant::now();
// Start with short intervals for fast state transitions, then back off.
let mut poll_interval = Duration::from_millis(1);
let max_interval = Duration::from_millis(50);
loop {
if let Some(ref vm) = self.vz_vm {
let state = vm.state();
tracing::debug!(
"VM {} current state: {:?}, target: {:?}",
self.id,
state,
target
);
if state == target {
return Ok(());
}
if state == VirtualMachineState::Error {
return Err(HypervisorError::VmError(
"VM entered error state".to_string(),
));
}
}
if start.elapsed() > timeout {
if let Some(ref vm) = self.vz_vm {
let state = vm.state();
return Err(HypervisorError::timeout(format!(
"Timed out waiting for VM state {target:?}, current state: {state:?}"
)));
}
return Err(HypervisorError::timeout("Timed out waiting for VM state"));
}
std::thread::sleep(poll_interval);
// Progressive backoff: 1ms → 2ms → 4ms → ... → 50ms cap.
poll_interval = (poll_interval * 2).min(max_interval);
}
}
/// Waits for the VM to reach the Stopped state within `timeout`.
///
/// Returns `Ok(true)` if stopped, `Ok(false)` on timeout.
pub fn wait_for_stopped(&self, timeout: Duration) -> Result<bool, HypervisorError> {
match self.wait_for_state(VirtualMachineState::Stopped, timeout) {
Ok(()) => Ok(true),
Err(e) => {
tracing::warn!("VM {} did not stop within {:?}: {}", self.id, timeout, e);
Ok(false)
}
}
}
/// Non-blocking read of all available data from a serial port file descriptor.
fn read_serial_fd(read_fd: RawFd) -> String {
// SAFETY: All fd operations use valid pipe fds from setup_serial_console().
// Flags are saved and restored to avoid side effects.
unsafe {
let flags = libc::fcntl(read_fd, libc::F_GETFL);
if flags == -1 {
let errno = *libc::__error();
tracing::warn!("fcntl F_GETFL failed on fd {}: errno={}", read_fd, errno);
return String::new();
}
if libc::fcntl(read_fd, libc::F_SETFL, flags | libc::O_NONBLOCK) == -1 {
let errno = *libc::__error();
tracing::warn!("fcntl F_SETFL failed on fd {}: errno={}", read_fd, errno);
return String::new();
}
let mut buffer = vec![0u8; 4096];
let mut output = String::new();
loop {
let bytes_read = libc::read(
read_fd,
buffer.as_mut_ptr() as *mut libc::c_void,
buffer.len(),
);
if bytes_read > 0 {
if let Ok(s) = std::str::from_utf8(&buffer[..bytes_read as usize]) {
output.push_str(s);
}
} else if bytes_read == 0 {
break;
} else {
let errno = *libc::__error();
if errno != libc::EAGAIN && errno != libc::EWOULDBLOCK {
tracing::warn!("Serial read error on fd {}: errno={}", read_fd, errno);
}
break;
}
}
if libc::fcntl(read_fd, libc::F_SETFL, flags) == -1 {
let errno = *libc::__error();
tracing::warn!(
"fcntl F_SETFL restore failed on fd {}: errno={}",
read_fd,
errno
);
}
output
}
}
/// Reads available console output (hvc0) from the guest.
pub fn read_console_output(&self) -> Result<String, HypervisorError> {
let (read_fd, _) = self
.console_fds
.ok_or_else(|| HypervisorError::DeviceError("Console not configured".to_string()))?;
Ok(Self::read_serial_fd(read_fd))
}
/// Reads available agent log output (hvc1) from the guest.
pub fn read_agent_log_output(&self) -> Result<String, HypervisorError> {
let (read_fd, _) = self.agent_log_fds.ok_or_else(|| {
HypervisorError::DeviceError("Agent log port not configured".to_string())
})?;
Ok(Self::read_serial_fd(read_fd))
}
/// Writes input to the console (hvc0).
pub fn write_console_input(&self, input: &str) -> Result<usize, HypervisorError> {
let (_, write_fd) = self
.console_fds
.ok_or_else(|| HypervisorError::DeviceError("Console not configured".to_string()))?;
// SAFETY: write_fd is a valid pipe fd from setup_serial_console().
unsafe {
let bytes_written =
libc::write(write_fd, input.as_ptr() as *const libc::c_void, input.len());
if bytes_written < 0 {
return Err(HypervisorError::DeviceError(format!(
"Failed to write to console: errno={}",
*libc::__error()
)));
}
Ok(bytes_written as usize)
}
}
/// Returns the path to the slave PTY device.
///
/// This can be used with tools like `screen` or `minicom` to connect
/// to the VM's serial console interactively.
pub fn console_path(&self) -> Option<String> {
self.console_fds
.map(|(master_fd, _)| unsafe {
let slave_name = libc::ptsname(master_fd);
if slave_name.is_null() {
String::new()
} else {
std::ffi::CStr::from_ptr(slave_name)
.to_string_lossy()
.into_owned()
}
})
.filter(|s| !s.is_empty())
}
/// Connects to a vsock port on the guest.
///
/// This establishes a vsock connection to the specified port number
/// on the guest VM. The VM must be running and have a vsock device
/// configured.
///
/// # Arguments
/// * `port` - The port number to connect to (e.g., 1024 for agent)
///
/// # Returns
/// A file descriptor for the connection that can be used for I/O.
///
/// # Errors
/// Returns an error if the VM is not running, no vsock device is
/// configured, or the connection fails.
pub fn connect_vsock(&self, port: u32) -> Result<std::os::unix::io::RawFd, HypervisorError> {
// Check VM is running
let state = self.state();
if state != VmState::Running {
return Err(HypervisorError::VmStateError {
expected: "Running".to_string(),
actual: format!("{state:?}"),
});
}
// Get the VZ VM's socket devices using arcbox-vz API
let vz_vm = self
.vz_vm
.as_ref()
.ok_or_else(|| HypervisorError::VmError("No VZ VM instance".to_string()))?;
let socket_devices = vz_vm.socket_devices();
let socket_device = socket_devices.first().ok_or_else(|| {
HypervisorError::DeviceError("No vsock device configured".to_string())
})?;
// Connect to the port using arcbox-vz's blocking connect.
tracing::debug!("Connecting to vsock port {} on VM {}", port, self.id);
let connection = socket_device
.connect_blocking(port, std::time::Duration::from_secs(10))
.map_err(|e| HypervisorError::DeviceError(format!("vsock connect failed: {e}")))?;
// Get the raw fd and take ownership (prevents close on drop)
let fd = connection.into_raw_fd();
tracing::debug!("Connected to vsock port {}, fd={}", port, fd);
Ok(fd)
}
/// Returns the VM ID.
#[must_use]
pub const fn id(&self) -> u64 {
self.id
}
/// Returns the VM configuration.
#[must_use]
pub const fn config(&self) -> &VmConfig {
&self.config
}
/// Returns the current VM state.
pub fn state(&self) -> VmState {
*self.state.read().unwrap()
}
/// Returns whether the VM is running.
#[must_use]
pub fn is_running(&self) -> bool {
self.running.load(Ordering::SeqCst)
}
/// Sets the VM state.
fn set_state(&self, new_state: VmState) {
let mut state = self.state.write().unwrap();
tracing::debug!("VM {} state: {:?} -> {:?}", self.id, *state, new_state);
*state = new_state;
}
// ========================================================================
// IRQ Injection Interface (Darwin)
//
// NOTE: Apple's Virtualization.framework does NOT expose interrupt injection
// APIs. VirtIO device interrupts are handled internally by the framework.
//
// For custom devices that need interrupt injection, we use vsock-based
// signaling as an alternative. The host sends IRQ signals through a
// vsock connection, and the guest agent handles them.
//
// Protocol: [opcode(1)] [gsi(4)] [level(1)]
// - opcode 0x01: set_irq_line
// - opcode 0x02: trigger_edge_irq
// ========================================================================
/// IRQ signal opcodes for vsock protocol.
const IRQ_OPCODE_SET_LINE: u8 = 0x01;
const IRQ_OPCODE_EDGE_TRIGGER: u8 = 0x02;
/// Sets up vsock-based IRQ signaling.
///
/// This establishes a vsock connection to the guest agent on the reserved
/// IRQ signal port. Once established, `set_irq_line` and `trigger_edge_irq`
/// will send signals through this connection.
///
/// # Note
/// The VM must be running and have a vsock device configured.
/// The guest agent must be listening on `VSOCK_IRQ_SIGNAL_PORT`.
pub fn setup_irq_signaling(&self) -> Result<(), HypervisorError> {
// Check if already set up
{
let irq_fd = self.vsock_irq_fd.read().unwrap();
if irq_fd.is_some() {
tracing::debug!("IRQ signaling already set up for VM {}", self.id);
return Ok(());
}
}
tracing::info!(
"Setting up vsock-based IRQ signaling for VM {} on port {}",
self.id,
VSOCK_IRQ_SIGNAL_PORT
);
let fd = self.connect_vsock(VSOCK_IRQ_SIGNAL_PORT)?;
let mut irq_fd = self.vsock_irq_fd.write().unwrap();
*irq_fd = Some(fd);
tracing::info!("IRQ signaling established for VM {}, fd={}", self.id, fd);
Ok(())
}
/// Tears down vsock-based IRQ signaling.
pub fn teardown_irq_signaling(&self) {
let mut irq_fd = self.vsock_irq_fd.write().unwrap();
if let Some(fd) = irq_fd.take() {
tracing::debug!("Closing IRQ signaling fd {} for VM {}", fd, self.id);
unsafe {
libc::close(fd);
}
}
}
/// Sends an IRQ signal through the vsock connection.
///
/// Returns true if the signal was sent successfully, false if no IRQ
/// signaling connection is established.
fn send_irq_signal(&self, opcode: u8, gsi: u32, level: bool) -> bool {
let irq_fd = self.vsock_irq_fd.read().unwrap();
if let Some(fd) = *irq_fd {
// Protocol: [opcode(1)] [gsi(4 LE)] [level(1)]
let mut buf = [0u8; 6];
buf[0] = opcode;
buf[1..5].copy_from_slice(&gsi.to_le_bytes());
buf[5] = u8::from(level);
let written = unsafe { libc::write(fd, buf.as_ptr() as *const libc::c_void, 6) };
if written == 6 {
tracing::trace!(
"Sent IRQ signal: opcode={}, gsi={}, level={} on VM {}",
opcode,
gsi,
level,
self.id
);
return true;
}
tracing::warn!(
"Failed to send IRQ signal on VM {}: wrote {} bytes instead of 6",
self.id,
written
);
}
false
}
/// Sets the IRQ line level.
///
/// If vsock-based IRQ signaling is established (via `setup_irq_signaling`),
/// this sends a signal to the guest agent. Otherwise, it falls back to
/// logging a warning since Virtualization.framework doesn't expose direct
/// IRQ injection.
pub fn set_irq_line(&self, gsi: u32, level: bool) -> Result<(), HypervisorError> {
// Try vsock-based signaling first
if self.send_irq_signal(Self::IRQ_OPCODE_SET_LINE, gsi, level) {
return Ok(());
}
// Fall back to warning
tracing::warn!(
"set_irq_line(gsi={}, level={}) called on Darwin VM {} - \
no IRQ signaling connection, call setup_irq_signaling() first",
gsi,
level,
self.id
);
Ok(())
}
/// Triggers an edge-triggered interrupt.
///
/// If vsock-based IRQ signaling is established, this sends a signal to
/// the guest agent. Otherwise, it logs a warning.
pub fn trigger_edge_irq(&self, gsi: u32) -> Result<(), HypervisorError> {
// Try vsock-based signaling first (level is always true for edge-triggered)
if self.send_irq_signal(Self::IRQ_OPCODE_EDGE_TRIGGER, gsi, true) {
return Ok(());
}
// Fall back to warning
tracing::warn!(
"trigger_edge_irq(gsi={}) called on Darwin VM {} - \
no IRQ signaling connection, call setup_irq_signaling() first",
gsi,
self.id
);
Ok(())
}
/// Registers an eventfd for IRQ injection.
///
/// On Darwin, this is not supported. Use vsock-based signaling instead
/// by calling `setup_irq_signaling()` and then `set_irq_line()`.
pub fn register_irqfd(
&self,
_eventfd: RawFd,
gsi: u32,
_resample_fd: Option<RawFd>,
) -> Result<(), HypervisorError> {
tracing::warn!(
"register_irqfd(gsi={}) called on Darwin VM {} - not supported, \
use setup_irq_signaling() + set_irq_line() for IRQ injection",
gsi,
self.id
);
Err(HypervisorError::DeviceError(
"IRQFD not supported on Darwin - use vsock-based IRQ signaling".to_string(),
))
}
/// Unregisters an eventfd (not supported on Darwin).
pub fn unregister_irqfd(&self, _eventfd: RawFd, gsi: u32) -> Result<(), HypervisorError> {
tracing::warn!(
"unregister_irqfd(gsi={}) called on Darwin VM {} - not supported",
gsi,
self.id
);
Ok(())
}
// ========================================================================
// Memory Balloon Interface
//
// The VirtIO balloon device allows the host to dynamically manage guest
// memory by "inflating" (reclaiming memory) or "deflating" (returning
// memory). This helps achieve the <150MB idle memory target.
// ========================================================================
/// Returns whether a balloon device is configured for this VM.
#[must_use]
pub const fn has_balloon_device(&self) -> bool {
self.balloon_configured
}
/// Sets the target memory size for the balloon device.
///
/// The balloon device will inflate or deflate to reach the target:
/// - **Smaller target**: Balloon inflates, reclaiming memory from guest
/// - **Larger target**: Balloon deflates, returning memory to guest
///
/// # Arguments
/// * `target_bytes` - Target memory size in bytes. Should be between
/// the minimum memory size and the VM's configured memory size.
///
/// # Errors
/// Returns an error if the VM is not running or no balloon device is configured.
pub fn set_balloon_target_memory(&self, target_bytes: u64) -> Result<(), HypervisorError> {
let state = self.state();
if state != VmState::Running {
return Err(HypervisorError::VmStateError {
expected: "Running".to_string(),
actual: format!("{state:?}"),
});
}
if !self.balloon_configured {
return Err(HypervisorError::DeviceError(
"No balloon device configured".to_string(),
));
}
let vz_vm = self
.vz_vm
.as_ref()
.ok_or_else(|| HypervisorError::DeviceError("VM not finalized".to_string()))?;
let balloon = vz_vm.first_balloon_device().ok_or_else(|| {
HypervisorError::DeviceError("No balloon device found on running VM".to_string())
})?;
balloon.set_target_memory_size(target_bytes);
tracing::debug!(
"VM {}: set balloon target memory to {} bytes ({}MB)",
self.id,
target_bytes,
target_bytes / (1024 * 1024)
);
Ok(())
}
/// Gets the current target memory size from the balloon device.
///
/// Returns the target memory size in bytes, or 0 if no balloon is configured
/// or the VM is not running.
#[must_use]
pub fn get_balloon_target_memory(&self) -> u64 {
if self.state() != VmState::Running || !self.balloon_configured {
return 0;
}
self.vz_vm
.as_ref()
.and_then(arcbox_vz::VirtualMachine::first_balloon_device)
.map_or(0, |balloon| balloon.target_memory_size())
}
/// Returns the configured memory size for this VM.
///
/// This is the maximum memory the guest can use when the balloon is fully deflated.
#[must_use]
pub const fn configured_memory_size(&self) -> u64 {
self.config.memory_size
}
/// Adds a Rosetta x86_64 translation directory share to the VM.
///
/// Exposes Apple's Rosetta binary as a VirtioFS share (tag: "rosetta").
/// The guest mounts this and registers the binary via binfmt_misc to
/// transparently run x86_64 ELF binaries at near-native speed.
///
/// No-op (with warning) if Rosetta is not available on the host.
pub fn add_rosetta_share(&mut self) -> Result<(), HypervisorError> {
let availability = LinuxRosettaDirectoryShare::availability();
match availability {
RosettaAvailability::NotSupported => {
tracing::warn!("Rosetta not supported on this platform (Intel Mac or macOS < 13)");
return Ok(());
}
RosettaAvailability::NotInstalled => {
tracing::warn!(
"Rosetta not installed — run `softwareupdate --install-rosetta` to enable x86_64 support"
);
return Ok(());
}
RosettaAvailability::Supported => {}
}
let vz_config = self
.vz_config
.as_mut()
.ok_or_else(|| HypervisorError::VmStateError {
expected: "Created (config available)".to_string(),
actual: "config already consumed".to_string(),
})?;
let rosetta_share = match LinuxRosettaDirectoryShare::new() {
Ok(share) => share,
Err(e) => {
tracing::warn!("Failed to create Rosetta directory share: {e}");
return Ok(());
}
};
let mut fs_device = match VirtioFileSystemDeviceConfiguration::new("rosetta") {
Ok(device) => device,
Err(e) => {
tracing::warn!("Failed to create Rosetta VirtioFS device: {e}");
return Ok(());
}
};
fs_device.set_share(rosetta_share);
vz_config.add_directory_share(fs_device);
tracing::info!("Added Rosetta x86_64 translation share (tag: rosetta)");
Ok(())
}
}
impl VirtualMachine for DarwinVm {
type Vcpu = DarwinVcpu;
type Memory = DarwinMemory;
fn is_managed_execution(&self) -> bool {
// Darwin Virtualization.framework manages vCPU execution internally
true
}
fn memory(&self) -> &Self::Memory {
&self.memory
}
fn create_vcpu(&mut self, id: u32) -> Result<Self::Vcpu, HypervisorError> {
if id >= self.config.vcpu_count as u32 {
return Err(HypervisorError::VcpuCreationFailed {
id,
reason: format!(
"vCPU ID {} exceeds configured count {}",
id, self.config.vcpu_count
),
});
}
// Check if already created
{
let vcpus = self
.vcpus
.read()
.map_err(|_| HypervisorError::VcpuCreationFailed {
id,
reason: "Lock poisoned".to_string(),
})?;
if vcpus.contains(&id) {
return Err(HypervisorError::VcpuCreationFailed {
id,
reason: "vCPU already created".to_string(),
});
}
}
// Create vCPU for managed execution.
// On Virtualization.framework, vCPU execution is managed internally by the framework.
// The vCPU struct is a lightweight handle that tracks vCPU ID and state.
// NOTE: We pass null_mut() because arcbox-vz doesn't expose VM's raw pointer.
// The VM state is queried through the DarwinVm's state() method instead.
let vcpu = DarwinVcpu::new_managed(id, std::ptr::null_mut());
// Record creation
{
let mut vcpus =
self.vcpus
.write()
.map_err(|_| HypervisorError::VcpuCreationFailed {
id,
reason: "Lock poisoned".to_string(),
})?;
vcpus.push(id);
}
tracing::debug!("Created vCPU {} for VM {} (managed execution)", id, self.id);
Ok(vcpu)
}
fn add_virtio_device(&mut self, device: VirtioDeviceConfig) -> Result<(), HypervisorError> {
// Check state
let state = self.state();
if state != VmState::Created {
return Err(HypervisorError::DeviceError(
"Cannot add device: VM not in Created state".to_string(),
));
}
// Get mutable reference to config
let vz_config = self.vz_config.as_mut().ok_or_else(|| {
HypervisorError::DeviceError("VZ configuration not available".to_string())
})?;
match device.device_type {
VirtioDeviceType::Block => {
// Create block device using arcbox-vz API
if let Some(ref path) = device.path {
let storage_device =
StorageDeviceConfiguration::disk_image(path, device.read_only)
.map_err(|e| HypervisorError::DeviceError(e.to_string()))?;
vz_config.add_storage_device(storage_device);
tracing::debug!("Added block device: {}", path);
}
}
VirtioDeviceType::Net => {
let network_device = if let Some(fd) = device.net_fd {
// File-handle attachment: host owns the full network stack.
match device.mac_address.as_deref() {
Some(mac) => NetworkDeviceConfiguration::file_handle_with_mac(fd, mac),
None => NetworkDeviceConfiguration::file_handle(fd),
}
.map_err(|e| HypervisorError::DeviceError(e.to_string()))?
} else {
// Fallback to Apple's built-in NAT attachment.
match device.mac_address.as_deref() {
Some(mac_address) => NetworkDeviceConfiguration::nat_with_mac(mac_address)
.map_err(|e| HypervisorError::DeviceError(e.to_string()))?,
None => NetworkDeviceConfiguration::nat()
.map_err(|e| HypervisorError::DeviceError(e.to_string()))?,
}
};
vz_config.add_network_device(network_device);
tracing::debug!(
mac_address = device.mac_address.as_deref().unwrap_or("random"),
"Added network device (file_handle={})",
device.net_fd.is_some()
);
}
VirtioDeviceType::Console => {
// Console is handled separately via setup_serial_console()
tracing::debug!("Console device will be configured separately");
}
VirtioDeviceType::Fs => {
// Create filesystem device using arcbox-vz API
if let (Some(path), Some(tag)) = (&device.path, &device.tag) {
let directory = SharedDirectory::new(path, device.read_only)
.map_err(|e| HypervisorError::DeviceError(e.to_string()))?;
let share = SingleDirectoryShare::new(directory)
.map_err(|e| HypervisorError::DeviceError(e.to_string()))?;
let mut fs_device = VirtioFileSystemDeviceConfiguration::new(tag)
.map_err(|e| HypervisorError::DeviceError(e.to_string()))?;
fs_device.set_share(share);
vz_config.add_directory_share(fs_device);
tracing::debug!("Added filesystem device: {} -> {}", tag, path);
}
}
VirtioDeviceType::Vsock => {
// Create vsock device using arcbox-vz API
let socket_device = SocketDeviceConfiguration::new()
.map_err(|e| HypervisorError::DeviceError(e.to_string()))?;
vz_config.add_socket_device(socket_device);
tracing::debug!("Added vsock device");
}
VirtioDeviceType::Rng => {
// Entropy device is already added in new()
tracing::debug!("Entropy device already configured");
}
VirtioDeviceType::Balloon => {
// Mark balloon as configured
// NOTE: arcbox-vz does not yet support balloon device configuration
self.balloon_configured = true;
tracing::debug!("Balloon device configured (pending arcbox-vz support)");
}
_ => {
// Other device types (Gpu) not yet supported on Darwin
tracing::warn!(
"Device type {:?} not supported on Darwin",
device.device_type
);
}
}
tracing::debug!("Added {:?} device to VM {}", device.device_type, self.id);
// Store device configuration for snapshot/restore
self.device_configs.push(device);
Ok(())
}
fn start(&mut self) -> Result<(), HypervisorError> {
let state = self.state();
if state != VmState::Created && state != VmState::Stopped {
return Err(HypervisorError::VmStateError {
expected: "Created or Stopped".to_string(),
actual: format!("{state:?}"),
});
}
self.set_state(VmState::Starting);
// Finalize configuration if VM hasn't been created yet
if self.vz_vm.is_none() {
// Enable serial console for boot diagnostics unless already configured.
if self.console_fds.is_none() {
if let Err(err) = self.setup_serial_console() {
tracing::warn!("Failed to set up serial console: {}", err);
}
}
self.finalize_configuration()?;
}
// Start the VM using arcbox-vz's async API
if let Some(ref vm) = self.vz_vm {
tracing::debug!("Starting VM {} asynchronously...", self.id);
// Get tokio runtime handle for async operations
let rt = tokio::runtime::Handle::try_current().map_err(|_| {
self.set_state(VmState::Error);
HypervisorError::VmError("No tokio runtime available for VM start".to_string())
})?;
// Start the VM using arcbox-vz's async start
// Use block_in_place to allow blocking in async context
tokio::task::block_in_place(|| rt.block_on(vm.start())).map_err(|e| {
self.set_state(VmState::Error);
HypervisorError::VmError(format!("Failed to start VM: {e}"))
})?;
tracing::debug!("Waiting for VM {} to reach Running state...", self.id);
// Wait for VM to reach Running state
match self.wait_for_state(VirtualMachineState::Running, Duration::from_secs(30)) {
Ok(()) => {
self.running.store(true, Ordering::SeqCst);
self.set_state(VmState::Running);
tracing::info!("Started VM {}", self.id);
if let Some(path) = self.console_path() {
tracing::info!("Serial console attached at {}", path);
}
Ok(())
}
Err(e) => {
// Check actual VM state for better error message
if let Some(ref vz) = self.vz_vm {
let state = vz.state();
tracing::error!(
"VM {} failed to start, current state: {:?}",
self.id,
state
);
}
self.set_state(VmState::Error);
Err(e)
}
}
} else {
self.set_state(VmState::Error);
Err(HypervisorError::VmError("No VZ VM instance".to_string()))
}
}
fn pause(&mut self) -> Result<(), HypervisorError> {
let state = self.state();
if state != VmState::Running {
return Err(HypervisorError::VmStateError {
expected: "Running".to_string(),
actual: format!("{state:?}"),
});
}
if let Some(ref vm) = self.vz_vm {
// Get tokio runtime handle for async operations
let rt = tokio::runtime::Handle::try_current().map_err(|_| {
HypervisorError::VmError("No tokio runtime available for VM pause".to_string())
})?;
// Pause using arcbox-vz's async pause
// Use block_in_place to allow blocking in async context
tokio::task::block_in_place(|| rt.block_on(vm.pause()))
.map_err(|e| HypervisorError::VmError(format!("Failed to pause VM: {e}")))?;
self.wait_for_state(VirtualMachineState::Paused, Duration::from_secs(10))?;
}
self.set_state(VmState::Paused);
tracing::info!("Paused VM {}", self.id);
Ok(())
}
fn resume(&mut self) -> Result<(), HypervisorError> {
let state = self.state();
if state != VmState::Paused {
return Err(HypervisorError::VmStateError {
expected: "Paused".to_string(),
actual: format!("{state:?}"),
});
}
if let Some(ref vm) = self.vz_vm {
// Get tokio runtime handle for async operations
let rt = tokio::runtime::Handle::try_current().map_err(|_| {
HypervisorError::VmError("No tokio runtime available for VM resume".to_string())
})?;
// Resume using arcbox-vz's async resume
// Use block_in_place to allow blocking in async context
tokio::task::block_in_place(|| rt.block_on(vm.resume()))
.map_err(|e| HypervisorError::VmError(format!("Failed to resume VM: {e}")))?;
self.wait_for_state(VirtualMachineState::Running, Duration::from_secs(10))?;
}
self.set_state(VmState::Running);
tracing::info!("Resumed VM {}", self.id);
Ok(())
}
fn stop(&mut self) -> Result<(), HypervisorError> {
let state = self.state();
if state != VmState::Running && state != VmState::Paused {
return Err(HypervisorError::VmStateError {
expected: "Running or Paused".to_string(),
actual: format!("{state:?}"),
});
}
self.set_state(VmState::Stopping);
if let Some(ref vm) = self.vz_vm {
// Check if VM can be stopped
let can_stop = vm.can_stop();
tracing::debug!("VM {} can_stop: {}", self.id, can_stop);
if can_stop {
// Get tokio runtime handle for async operations
let rt = tokio::runtime::Handle::try_current().ok();
if let Some(rt) = rt {
// Stop using arcbox-vz's async stop
// Use block_in_place to allow blocking in async context
match tokio::task::block_in_place(|| rt.block_on(vm.stop())) {
Ok(()) => {
tracing::debug!("VM {} stop completed", self.id);
}
Err(e) => {
tracing::warn!("VM {} stop failed: {}", self.id, e);
// Continue with cleanup even if stop fails
}
}
} else {
// Guest shutdown is handled by the vsock shutdown RPC at
// the VmManager layer. Without a tokio runtime we cannot
// call the async VZ stop — the VM will be force-stopped
// by process exit.
tracing::debug!("VM {} no tokio runtime for async stop", self.id);
}
// Wait for VM to reach Stopped state
match self.wait_for_state(VirtualMachineState::Stopped, Duration::from_secs(10)) {
Ok(()) => {
tracing::debug!("VM {} reached Stopped state", self.id);
}
Err(e) => {
tracing::warn!("VM {} stop wait failed: {}", self.id, e);
// Continue with cleanup even if wait fails
}
}
} else {
tracing::warn!(
"VM {} cannot be stopped (canStop=false), forcing state change",
self.id
);
}
}
self.running.store(false, Ordering::SeqCst);
self.set_state(VmState::Stopped);
tracing::info!("Stopped VM {}", self.id);
Ok(())
}
fn as_any(&self) -> &dyn std::any::Any {
self
}
fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
self
}
fn vcpu_count(&self) -> u32 {
self.config.vcpu_count as u32
}
fn snapshot_devices(&self) -> Result<Vec<DeviceSnapshot>, HypervisorError> {
// Darwin Virtualization.framework does not expose internal device state.
// However, we store the device configuration metadata which allows:
// 1. Verifying device configuration matches on restore
// 2. Re-creating devices with the same configuration
//
// The `state` field contains serialized VirtioDeviceConfig.
let mut snapshots = Vec::new();
for (idx, config) in self.device_configs.iter().enumerate() {
// Serialize the device configuration to JSON bytes
let state = serde_json::to_vec(config).unwrap_or_default();
let name = match config.device_type {
VirtioDeviceType::Block => {
if let Some(ref path) = config.path {
format!(
"block-{}-{}",
idx,
path.rsplit('/').next().unwrap_or("disk")
)
} else {
format!("block-{idx}")
}
}
VirtioDeviceType::Net => format!("net-{idx}"),
VirtioDeviceType::Console => "console-0".to_string(),
VirtioDeviceType::Fs => {
if let Some(ref tag) = config.tag {
format!("fs-{tag}")
} else {
format!("fs-{idx}")
}
}
VirtioDeviceType::Vsock => "vsock-0".to_string(),
_ => format!("device-{idx}"),
};
snapshots.push(DeviceSnapshot {
device_type: config.device_type,
name,
state,
});
}
// Record serial ports if configured (not in device_configs).
if self.console_fds.is_some() {
snapshots.push(DeviceSnapshot {
device_type: VirtioDeviceType::Console,
name: "serial-0".to_string(),
state: Vec::new(),
});
}
if self.agent_log_fds.is_some() {
snapshots.push(DeviceSnapshot {
device_type: VirtioDeviceType::Console,
name: "serial-1".to_string(),
state: Vec::new(),
});
}
tracing::debug!(
"snapshot_devices: captured {} device configurations for VM {}",
snapshots.len(),
self.id
);
Ok(snapshots)
}
fn restore_devices(&mut self, snapshots: &[DeviceSnapshot]) -> Result<(), HypervisorError> {
// Darwin Virtualization.framework does not support live device state restore.
// However, we can validate that the snapshot device configuration matches
// the current VM configuration.
//
// For actual device restore, the VM should be recreated with the same
// configuration from the snapshot metadata.
tracing::info!(
"restore_devices: validating {} devices for VM {}",
snapshots.len(),
self.id
);
// Deserialize and validate device configurations
let mut mismatches = Vec::new();
for snapshot in snapshots {
// Try to deserialize the stored configuration
if !snapshot.state.is_empty() {
if let Ok(stored_config) =
serde_json::from_slice::<VirtioDeviceConfig>(&snapshot.state)
{
// Find matching device in current configuration
let matches = self.device_configs.iter().any(|current| {
current.device_type == stored_config.device_type
&& current.path == stored_config.path
&& current.tag == stored_config.tag
});
if !matches {
mismatches.push(format!(
"{:?} device '{}' (path={:?}, tag={:?})",
stored_config.device_type,
snapshot.name,
stored_config.path,
stored_config.tag
));
}
}
}
}
if !mismatches.is_empty() {
tracing::warn!(
"restore_devices: {} device(s) in snapshot don't match current configuration: {:?}",
mismatches.len(),
mismatches
);
}
// Verify device count by type
let snapshot_blocks = snapshots
.iter()
.filter(|s| s.device_type == VirtioDeviceType::Block)
.count();
let snapshot_nets = snapshots
.iter()
.filter(|s| s.device_type == VirtioDeviceType::Net)
.count();
let current_blocks = self
.device_configs
.iter()
.filter(|c| c.device_type == VirtioDeviceType::Block)
.count();
let current_nets = self
.device_configs
.iter()
.filter(|c| c.device_type == VirtioDeviceType::Net)
.count();
if snapshot_blocks != current_blocks {
tracing::warn!(
"Block device count mismatch: snapshot has {}, current VM has {}",
snapshot_blocks,
current_blocks
);
}
if snapshot_nets != current_nets {
tracing::warn!(
"Network device count mismatch: snapshot has {}, current VM has {}",
snapshot_nets,
current_nets
);
}
Ok(())
}
}
impl Drop for DarwinVm {
fn drop(&mut self) {
// Stop VM if running, unless the caller has already handled shutdown
// and set skip_stop_on_drop to avoid crashing the VF stop path.
if self.is_running() && !self.skip_stop_on_drop {
let _ = self.stop();
}
// Close serial FDs for both console ports.
for fds in [self.console_fds.take(), self.agent_log_fds.take()]
.into_iter()
.flatten()
{
// SAFETY: These are valid pipe fds from setup_serial_console().
unsafe {
libc::close(fds.0);
if fds.1 != fds.0 {
libc::close(fds.1);
}
}
}
// VZ handles and dispatch queue are automatically released by arcbox-vz's drop
tracing::debug!("Dropped VM {}", self.id);
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::traits::Vcpu;
use crate::types::CpuArch;
#[test]
fn test_vm_creation() {
if !arcbox_vz::is_supported() {
println!("Virtualization not supported, skipping");
return;
}
let config = VmConfig {
vcpu_count: 2,
memory_size: 512 * 1024 * 1024,
arch: CpuArch::native(),
..Default::default()
};
let vm = DarwinVm::new(config).unwrap();
assert_eq!(vm.state(), VmState::Created);
assert!(!vm.is_running());
}
#[test]
fn test_vcpu_creation() {
if !arcbox_vz::is_supported() {
println!("Virtualization not supported, skipping");
return;
}
let config = VmConfig {
vcpu_count: 4,
memory_size: 512 * 1024 * 1024,
..Default::default()
};
let mut vm = DarwinVm::new(config).unwrap();
// Create valid vCPUs
let vcpu0 = vm.create_vcpu(0);
assert!(vcpu0.is_ok());
assert_eq!(vcpu0.unwrap().id(), 0);
let vcpu1 = vm.create_vcpu(1);
assert!(vcpu1.is_ok());
// Try to create same vCPU again
let vcpu0_again = vm.create_vcpu(0);
assert!(vcpu0_again.is_err());
// Try to create vCPU with invalid ID
let vcpu99 = vm.create_vcpu(99);
assert!(vcpu99.is_err());
}
#[test]
fn test_vm_lifecycle() {
if !arcbox_vz::is_supported() {
println!("Virtualization not supported, skipping");
return;
}
let config = VmConfig {
vcpu_count: 1,
memory_size: 256 * 1024 * 1024,
..Default::default()
};
let mut vm = DarwinVm::new(config).unwrap();
assert_eq!(vm.state(), VmState::Created);
// Note: Actually starting the VM requires:
// 1. The process to be signed with com.apple.security.virtualization entitlement
// 2. Running on a thread with an active CFRunLoop
//
// For unit tests without proper signing, we can only verify state transitions
// up to the point of calling start(). The full lifecycle test requires
// a signed binary run from a GUI or properly configured CLI environment.
// Attempt to start - will fail without entitlement or kernel
match vm.start() {
Ok(()) => {
// If start succeeds, test full lifecycle
assert_eq!(vm.state(), VmState::Running);
assert!(vm.is_running());
// Pause
vm.pause().unwrap();
assert_eq!(vm.state(), VmState::Paused);
// Resume
vm.resume().unwrap();
assert_eq!(vm.state(), VmState::Running);
// Stop
vm.stop().unwrap();
assert_eq!(vm.state(), VmState::Stopped);
assert!(!vm.is_running());
}
Err(e) => {
// Expected without proper signing/configuration
println!("VM start failed (expected without entitlement): {}", e);
// VM should be in Error or Starting state
let state = vm.state();
assert!(
state == VmState::Starting || state == VmState::Error,
"Unexpected state after failed start: {:?}",
state
);
}
}
}
#[test]
fn test_invalid_state_transitions() {
if !arcbox_vz::is_supported() {
println!("Virtualization not supported, skipping");
return;
}
// Use a small fixed size — this test only checks state transitions,
// not actual guest execution.
let config = VmConfig {
memory_size: 128 * 1024 * 1024, // 128MB
..Default::default()
};
let mut vm = DarwinVm::new(config).unwrap();
// Can't pause if not running
assert!(vm.pause().is_err());
// Can't resume if not paused
assert!(vm.resume().is_err());
// Can't stop if not running
assert!(vm.stop().is_err());
}
#[test]
fn test_balloon_device_configuration() {
if !arcbox_vz::is_supported() {
println!("Virtualization not supported, skipping");
return;
}
let config = VmConfig {
vcpu_count: 1,
memory_size: 512 * 1024 * 1024,
..Default::default()
};
let mut vm = DarwinVm::new(config).unwrap();
// Initially no balloon device
assert!(!vm.has_balloon_device());
// Add balloon device
let balloon_config = VirtioDeviceConfig::balloon();
vm.add_virtio_device(balloon_config).unwrap();
// Now balloon should be configured
assert!(vm.has_balloon_device());
assert_eq!(vm.configured_memory_size(), 512 * 1024 * 1024);
// Before starting, balloon target memory should return 0
// (no running VM to query)
assert_eq!(vm.get_balloon_target_memory(), 0);
}
#[test]
fn test_balloon_device_pending() {
if !arcbox_vz::is_supported() {
println!("Virtualization not supported, skipping");
return;
}
// NOTE: Balloon device configuration is pending arcbox-vz support.
// Once arcbox-vz adds BalloonDeviceConfiguration, this test should
// verify that the balloon device can be created and configured.
println!("Balloon device test skipped: pending arcbox-vz support");
}
}