Skip to content

Commit 30ce395

Browse files
ppennaCopilot
andcommitted
virt: refuse to restore an element that the partition lacks
A decoded snapshot is external input, and can hold an element that the destination partition does not have: SynIC state for a microVM, whose partition has no Hyper-V enlightenments, an element for an MSR that the destination's KVM does not list, or the hypercall MSRs, the reference time, or the reference TSC page of the VM state. The generated restore_all asserted that each element it was about to set is present, so it panicked on such a snapshot after it had set the elements that precede the unsupported one, and, since OpenVMM builds with panic = "abort", the process died with no restore error (microsoft/nvx#1168). restore_all now checks every element of the saved state against the partition before it sets or commits any of them, and fails with the new StateError::Unsupported, which names the element in the phase "restore check" and has no source, since it fails before any backend access. StateError becomes an enum, whose Access variant keeps the phase and the backend's error as its source, so a backend failure is reported as before. Each restore_all call checks its own saved state, the VM's or one VP's, so a refusal for a later VP leaves the VM state and the earlier VPs restored, as any other failed restore does, and the restore still does not undo what it set before a setter fails. The change adds no saved element and changes no saved state, format, or version, and StateError is an in-memory error, not a saved one: a snapshot that restored restores as before, and one that held an unsupported element no longer panics. The Guide's snapshot chapters say that a restore can fail this way, where the format chapter said that it stops on an assertion, and the rules comment of the VP state's state_trait! says that a capability that a backend clears for a host also decides which hosts can restore a snapshot. Tests, in state::tests, with a test state whose second element the partition lacks: - a_restore_refuses_an_absent_element_before_it_changes_anything requires that the restore fails with Unsupported, names the phase and the element, has no source, and calls no setter or commit. At 359169f it panics with "assertion failed: <Absent as StateElement<Caps, Vp>>::is_present(self.caps())", after the setter of the first element ran. - a_restore_sets_the_elements_that_the_partition_has and a_failed_restore_keeps_the_error_of_the_backend pass before and after the change: the first sets the elements of a state that holds only what the partition has, and commits, and the second requires that the error of a failing setter stays its source. - a_refused_save_reads_nothing now matches the Access variant instead of reading the phase field. The 140 tests of virt pass with cargo nextest, with the ignored ones, on Windows x64 and on Linux x64 (nvx-kvm-test), and the 237 of virt and virt_mshv on nvx-mshv-test; virt_kvm, virt_mshv, and OpenHCL's virt_mshv_vtl, which cargo check type-checks for x86_64-unknown-linux- musl, build with the enum. cargo clippy --all-targets and cargo doc are clean for virt, and virt and virt_hvf type-check for aarch64-apple-darwin. The next commit adds the contract tests of the real backends. End to end, on Linux 6.18.57 with KVM (nvx-kvm-test) and with MSHV (nvx-mshv-test): a microVM snapshot that a guest captured, with state.bin edited to give VP 0 a SynIC element and manifest.bin to give its length, restores as follows. OpenVMM at 359169f aborts, with SIGABRT and no restore error: "thread 'vp-0' panicked at vmm_core/virt/src/x86/vp.rs:2576:1: assertion failed: <SyntheticMsrs as ...>::is_present(self.caps())". With this commit it exits with status 1 and reports "failed to launch vm worker: loadedvm restore failed: restore failed: {partition: failed to restore child device vp0: state access error, phase restore check: the saved state has "synic", which the partition does not support}", before any vCPU runs, and the unedited snapshot restores and its guest continues. The snapshot-core, snapshot-rollback, smp-snapshot, restore-processors, snapshot-tiers, and run-console-restore scenarios of test-microvm, on 1 and 2 vCPUs, and its smp-lapic, time-abi-conformance, restore-downtime, restore-memory, platform-restore-processors, and console-snapshot scenarios, on 1, 2, and 4, pass on both with this commit. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
1 parent 359169f commit 30ce395

4 files changed

Lines changed: 205 additions & 16 deletions

File tree

‎Guide/src/dev_guide/snapshot_format.md‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -289,7 +289,14 @@ clear their capabilities.
289289
A saved state restores only into a partition that has every element that it
290290
holds. A destination whose backend lacks one, such as a host whose KVM does not
291291
list `IA32_UMWAIT_CONTROL`, cannot give the guest the value that it saved, and
292-
`restore_all` does not drop the element: it stops on an assertion.
292+
`restore_all` does not drop the element: it checks every element of the saved
293+
state against the partition before it sets any of them, and refuses the restore
294+
with an error, in the phase `restore check`, that names the first element that
295+
the partition lacks. The refusal changes none of that VP's state, and the
296+
restore of the VM state checks its elements the same way. A snapshot reaches it
297+
only when it was edited or when the destination's backend cannot access an MSR
298+
that the capturing host's could, since a restore requires the backend and the
299+
CPU generation of the capture.
293300

294301
A restore of the machine-check state sets the banks that the saved state lists
295302
and puts the VP's other banks back as `bind` left them: with every error enabled

‎Guide/src/user_guide/openvmm/snapshots.md‎

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -289,6 +289,20 @@ the kind refuses a snapshot that holds one, which only a damaged or crafted
289289
snapshot of another backend does, since a restore requires the backend that
290290
captured the snapshot.
291291

292+
A restore also refuses a saved VM or vCPU state that holds an element that the
293+
partition does not have, such as SynIC state for a microVM, whose partition has
294+
no Hyper-V enlightenments, or an MSR that the destination's KVM does not list
295+
(see [VP state
296+
elements](../../dev_guide/snapshot_format.md#vp-state-elements)). A save holds
297+
only the elements that its partition has, so only a snapshot that was edited, or
298+
that a host captured whose backend could access an MSR that the destination's
299+
cannot, holds one. The restore of the VM state, and of each vCPU's state, checks
300+
all of its elements before it sets any of them. OpenVMM does not abort: the
301+
restore fails with an error in the phase `restore check` that names the first
302+
element that the partition lacks, and no vCPU runs. The refused state is left as
303+
it was, but the VM state and the other vCPUs' states may already be restored, so
304+
the VM is reset or discarded, as after any failed restore.
305+
292306
For a tiered microVM restore, and for a restore that replaces the network
293307
policy of a snapshot without a tier, OpenVMM starts device workers with
294308
network, control, and filesystem input gated. The guest performs post-restore
@@ -816,4 +830,5 @@ immediately with a clear error if any active device does not support it.
816830
VP has it, and a build that predates it ignores it in a later snapshot, so
817831
neither restore fails, and neither keeps what the guest wrote. Only a host
818832
whose KVM can access an MSR saves it, and a snapshot restores only on a host
819-
that can access every MSR that it holds.
833+
that can access every MSR that it holds: on another host, the restore is
834+
refused, with an error that names the element, before it changes the VP.

‎vmm_core/virt/src/state.rs‎

Lines changed: 176 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,9 @@ use thiserror::Error;
1313
pub trait StateElement<C, V>: Sized + Inspect + PartialEq {
1414
/// Returns whether this state is present for the partition, based on the
1515
/// partition capabilities.
16+
///
17+
/// A restore refuses a saved state that holds an element that is not
18+
/// present.
1619
fn is_present(caps: &C) -> bool;
1720

1821
/// Returns the value at VM reset.
@@ -56,12 +59,22 @@ pub trait HvRegisterState<T, const COUNT: usize>: Default {
5659
fn set_values(&mut self, it: impl Iterator<Item = HvRegisterValue>);
5760
}
5861

62+
/// An error from saving, restoring, or resetting state.
5963
#[derive(Debug, Error)]
60-
#[error("state access error, phase {phase}")]
61-
pub struct StateError<T: 'static + Debug + std::error::Error> {
62-
pub(crate) phase: &'static str,
63-
#[source]
64-
pub(crate) err: T,
64+
pub enum StateError<T: 'static + Debug + std::error::Error> {
65+
/// The partition failed to access the state, in `phase`.
66+
#[error("state access error, phase {phase}")]
67+
Access {
68+
phase: &'static str,
69+
#[source]
70+
err: T,
71+
},
72+
/// A restore refused a saved state that holds `element`, which the
73+
/// partition does not have, before it changed any state.
74+
#[error(
75+
"state access error, phase restore check: the saved state has {element:?}, which the partition does not support"
76+
)]
77+
Unsupported { element: &'static str },
6578
}
6679

6780
mod macros {
@@ -81,6 +94,11 @@ mod macros {
8194
/// A backend can refuse a save of a state that its pieces cannot hold by
8295
/// overriding `check_saveable`, which the generated `save_all` calls first.
8396
///
97+
/// The generated `restore_all` refuses a saved state that holds a piece
98+
/// that is missing for the partition, before it sets any piece, since a
99+
/// saved state is external input and its pieces are no proof of what the
100+
/// partition supports.
101+
///
84102
/// The intent is that the partition types implement these traits to get and
85103
/// set individual pieces of state.
86104
macro_rules! state_trait {
@@ -121,11 +139,11 @@ mod macros {
121139
/// Save all state that can be restored by a call to restore.
122140
#[allow(unused_mut)]
123141
fn save_all(&mut self) -> Result<$save_state, $crate::state::StateError<Self::Error>> {
124-
self.check_saveable().map_err(|err| $crate::state::StateError{phase: "save check", err})?;
142+
self.check_saveable().map_err(|err| $crate::state::StateError::Access{phase: "save check", err})?;
125143
let mut save_state = $save_state::default();
126144
$(
127145
if <$ty as $crate::state::StateElement<$caps, $vp>>::is_present(self.caps()) {
128-
save_state.$get = Some(self.$get().map_err(|err| $crate::state::StateError{phase: concat!("save ", stringify!($id)), err})?);
146+
save_state.$get = Some(self.$get().map_err(|err| $crate::state::StateError::Access{phase: concat!("save ", stringify!($id)), err})?);
129147
}
130148
)*
131149

@@ -134,17 +152,28 @@ mod macros {
134152

135153
/// Restore state elements saved in save state.
136154
///
155+
/// A saved state can hold an element that the partition does
156+
/// not have, as a decoded snapshot of another partition can.
157+
/// This checks every element of the saved state first, and
158+
/// fails without setting or committing anything if the
159+
/// partition lacks one. It does not undo the elements that it
160+
/// has set when a setter fails.
161+
///
137162
/// A debug build reads each element back after it sets it, and
138163
/// asserts that the state that it reads is the one that it set,
139164
/// up to the normalization that the element's `restore_eq`
140165
/// accepts.
141166
#[allow(unused_variables)]
142167
fn restore_all(&mut self, state: &$save_state) -> Result<(), $crate::state::StateError<Self::Error>> {
168+
$(
169+
if state.$get.is_some() && !<$ty as $crate::state::StateElement<$caps, $vp>>::is_present(self.caps()) {
170+
return Err($crate::state::StateError::Unsupported{element: $id});
171+
}
172+
)*
173+
143174
$(
144175
if let Some(value) = state.$get.as_ref() {
145-
// TODO: assert good or not?
146-
assert!(<$ty as $crate::state::StateElement<$caps, $vp>>::is_present(self.caps()));
147-
self.$set(value).map_err(|err| $crate::state::StateError{phase: concat!("restore ", stringify!($id)), err})?;
176+
self.$set(value).map_err(|err| $crate::state::StateError::Access{phase: concat!("restore ", stringify!($id)), err})?;
148177
if cfg!(debug_assertions) {
149178
if <$ty as $crate::state::StateElement<$caps, $vp>>::can_compare(self.caps()) {
150179
let restored = self.$get().expect($id);
@@ -159,14 +188,14 @@ mod macros {
159188
}
160189
)*
161190

162-
self.commit().map_err(|err| $crate::state::StateError{phase: "commit restore", err})
191+
self.commit().map_err(|err| $crate::state::StateError::Access{phase: "commit restore", err})
163192
}
164193

165194
/// Resets all the state elements to their initial state (after machine reset).
166195
fn reset_all(&mut self, vp_info: &$vp) -> Result<(), $crate::state::StateError<Self::Error>> {
167196
$(
168197
if <$ty as $crate::state::StateElement<$caps, $vp>>::is_present(self.caps()) {
169-
self.$set(&<$ty as $crate::state::StateElement<$caps, $vp>>::at_reset(self.caps(), vp_info)).map_err(|err| $crate::state::StateError{phase: concat!("reset ", stringify!($id)), err})?;
198+
self.$set(&<$ty as $crate::state::StateElement<$caps, $vp>>::at_reset(self.caps(), vp_info)).map_err(|err| $crate::state::StateError::Access{phase: concat!("reset ", stringify!($id)), err})?;
170199
}
171200
)*
172201

@@ -219,6 +248,7 @@ mod macros {
219248
#[expect(dead_code)]
220249
mod tests {
221250
use super::StateElement;
251+
use super::StateError;
222252
use super::state_trait;
223253
use inspect::Inspect;
224254
use mesh_protobuf::Protobuf;
@@ -441,7 +471,13 @@ mod tests {
441471
fn a_refused_save_reads_nothing() {
442472
let mut state = Refusing::default();
443473
let err = state.save_all().unwrap_err();
444-
assert_eq!(err.phase, "save check");
474+
assert!(matches!(
475+
err,
476+
StateError::Access {
477+
phase: "save check",
478+
..
479+
}
480+
));
445481
assert!(std::error::Error::source(&err).is_some_and(|err| err.is::<Error>()));
446482
assert_eq!(state.0.reads, ["check_saveable"]);
447483
}
@@ -602,4 +638,131 @@ mod tests {
602638
assert_eq!(partition.extra, Extra { value: 6 });
603639
}
604640
}
641+
642+
/// An element that the test partition does not have.
643+
#[derive(Debug, Copy, Clone, PartialEq, Eq, Protobuf, Inspect)]
644+
#[mesh(package = "virt.test")]
645+
pub struct Absent {
646+
#[mesh(1)]
647+
value: u32,
648+
}
649+
650+
impl StateElement<Caps, Vp> for Absent {
651+
fn is_present(_caps: &Caps) -> bool {
652+
false
653+
}
654+
655+
fn at_reset(_caps: &Caps, _vp: &Vp) -> Self {
656+
Self { value: 0 }
657+
}
658+
}
659+
660+
state_trait! {
661+
"Test state with an element that the partition lacks",
662+
AccessRestoreState,
663+
Caps,
664+
Vp,
665+
RestoreSavedState,
666+
"virt.test",
667+
(1, "number", number, set_number, Number),
668+
(2, "absent", absent, set_absent, Absent),
669+
}
670+
671+
/// A state that records each change that a restore makes.
672+
#[derive(Default)]
673+
struct Recording {
674+
number: u32,
675+
fail_set_number: bool,
676+
changes: Vec<&'static str>,
677+
}
678+
679+
impl AccessRestoreState for Recording {
680+
type Error = Error;
681+
682+
fn caps(&self) -> &Caps {
683+
&Caps
684+
}
685+
686+
fn commit(&mut self) -> Result<(), Error> {
687+
self.changes.push("commit");
688+
Ok(())
689+
}
690+
691+
fn number(&mut self) -> Result<Number, Error> {
692+
Ok(Number { value: self.number })
693+
}
694+
695+
fn set_number(&mut self, value: &Number) -> Result<(), Error> {
696+
if self.fail_set_number {
697+
return Err(Error);
698+
}
699+
self.changes.push("set_number");
700+
self.number = value.value;
701+
Ok(())
702+
}
703+
704+
fn absent(&mut self) -> Result<Absent, Error> {
705+
Err(Error)
706+
}
707+
708+
fn set_absent(&mut self, _value: &Absent) -> Result<(), Error> {
709+
self.changes.push("set_absent");
710+
Ok(())
711+
}
712+
}
713+
714+
#[test]
715+
fn a_restore_refuses_an_absent_element_before_it_changes_anything() {
716+
let mut state = Recording {
717+
number: 7,
718+
..Default::default()
719+
};
720+
// The number comes first in the restore order, so a restore that
721+
// checked the elements one by one would have set it.
722+
let err = state
723+
.restore_all(&RestoreSavedState {
724+
number: Some(Number { value: 1 }),
725+
absent: Some(Absent { value: 2 }),
726+
})
727+
.unwrap_err();
728+
assert_eq!(state.changes, Vec::<&str>::new());
729+
assert_eq!(state.number, 7);
730+
assert!(matches!(err, StateError::Unsupported { element: "absent" }));
731+
let message = err.to_string();
732+
assert!(
733+
message.contains("restore check") && message.contains("absent"),
734+
"{message}"
735+
);
736+
assert!(std::error::Error::source(&err).is_none());
737+
}
738+
739+
#[test]
740+
fn a_restore_sets_the_elements_that_the_partition_has() {
741+
let mut state = Recording::default();
742+
state
743+
.restore_all(&RestoreSavedState {
744+
number: Some(Number { value: 3 }),
745+
absent: None,
746+
})
747+
.unwrap();
748+
assert_eq!(state.changes, ["set_number", "commit"]);
749+
assert_eq!(state.number, 3);
750+
}
751+
752+
#[test]
753+
fn a_failed_restore_keeps_the_error_of_the_backend() {
754+
let mut state = Recording {
755+
fail_set_number: true,
756+
..Default::default()
757+
};
758+
let err = state
759+
.restore_all(&RestoreSavedState {
760+
number: Some(Number { value: 3 }),
761+
absent: None,
762+
})
763+
.unwrap_err();
764+
assert!(matches!(err, StateError::Access { .. }));
765+
assert!(std::error::Error::source(&err).is_some_and(|err| err.is::<Error>()));
766+
assert_eq!(state.changes, Vec::<&str>::new());
767+
}
605768
}

‎vmm_core/virt/src/x86/vp.rs‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2572,7 +2572,11 @@ impl StateElement<X86PartitionCapabilities, X86VpInfo> for NestedState {
25722572
// - a backend that can access the state on some hosts only sets or clears the
25732573
// capability for the host: the KVM backend clears it for an MSR that the
25742574
// host's `KVM_GET_MSR_INDEX_LIST` lacks, unless every host's KVM has the MSR
2575-
// and only some list it, as for `IA32_DEBUGCTL`.
2575+
// and only some list it, as for `IA32_DEBUGCTL`;
2576+
// - a restore into a partition for which `is_present` is false refuses a saved
2577+
// state that holds the element, before it sets any element, so a capability
2578+
// that a backend clears for a host also decides which hosts can restore a
2579+
// snapshot that holds the element.
25762580
state_trait! {
25772581
"Per-VP state",
25782582
AccessVpState,

0 commit comments

Comments
 (0)