Skip to main content

hyperlight_host/
error.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2025 The Hyperlight Authors.
3
4use std::array::TryFromSliceError;
5use std::cell::{BorrowError, BorrowMutError};
6use std::convert::Infallible;
7use std::error::Error;
8use std::num::TryFromIntError;
9use std::string::FromUtf8Error;
10use std::sync::{MutexGuard, PoisonError};
11use std::time::SystemTimeError;
12
13#[cfg(target_os = "windows")]
14use crossbeam_channel::{RecvError, SendError};
15use flatbuffers::InvalidFlatbuffer;
16use hyperlight_common::flatbuffer_wrappers::function_types::{ParameterValue, ReturnValue};
17use hyperlight_common::flatbuffer_wrappers::guest_error::ErrorCode;
18use hyperlight_common::virtq::VirtqError;
19use thiserror::Error;
20
21use crate::hypervisor::hyperlight_vm::HyperlightVmError;
22#[cfg(target_os = "windows")]
23use crate::hypervisor::wrappers::HandleWrapper;
24use crate::mem::memory_region::MemoryRegionFlags;
25use crate::mem::ptr::RawPtr;
26
27/// The error type for Hyperlight operations
28#[derive(Error, Debug)]
29pub enum HyperlightError {
30    /// Anyhow error
31    #[error("Anyhow Error was returned: {0}")]
32    AnyhowError(#[from] anyhow::Error),
33
34    /// Checked Add Overflow
35    #[error("Couldn't add offset to base address. Offset: {0}, Base Address: {1}")]
36    CheckedAddOverflow(u64, u64),
37
38    /// Cross beam channel receive error
39    #[error("{0:?}")]
40    #[cfg(target_os = "windows")]
41    CrossBeamReceiveError(#[from] RecvError),
42
43    /// Cross beam channel send error
44    #[error("{0:?}")]
45    #[cfg(target_os = "windows")]
46    CrossBeamSendError(#[from] SendError<HandleWrapper>),
47
48    /// CString conversion error
49    #[error("Error converting CString {0:?}")]
50    CStringConversionError(#[from] std::ffi::NulError),
51
52    /// A generic error with a message
53    #[error("{0}")]
54    Error(String),
55
56    /// The virtqueue transport cannot be used safely.
57    #[error("Virtqueue transport error: {0}")]
58    TransportError(String),
59
60    /// Execution violation
61    #[error("Non-executable address {0:#x} tried to be executed")]
62    ExecutionAccessViolation(u64),
63
64    /// Guest execution was cancelled by the host
65    #[error("Execution was cancelled by the host.")]
66    ExecutionCanceledByHost(),
67
68    /// Accessing the value of a flatbuffer parameter failed
69    #[error("Failed to get a value from flat buffer parameter")]
70    FailedToGetValueFromParameter(),
71
72    ///Field Name not found in decoded GuestLogData
73    #[error("Field Name {0} not found in decoded GuestLogData")]
74    FieldIsMissingInGuestLogData(String),
75
76    /// Guest aborted during outb
77    #[error("Guest aborted: {0} {1}")]
78    GuestAborted(u8, String),
79
80    /// Guest call resulted in error in guest
81    #[error("Guest error occurred {0:?}: {1}")]
82    GuestError(ErrorCode, String),
83
84    /// An attempt to cancel guest execution failed because it is hanging on a host function call
85    #[error("Guest execution hung on the execution of a host function call")]
86    GuestExecutionHungOnHostFunctionCall(),
87
88    /// Guest call already in progress
89    #[error("Guest call is already in progress")]
90    GuestFunctionCallAlreadyInProgress(),
91
92    /// The given type is not supported by the guest interface.
93    #[error("Unsupported type: {0}")]
94    GuestInterfaceUnsupportedType(String),
95
96    /// The guest binary was built with a different hyperlight-guest-bin version than the host expects.
97    /// Hyperlight currently provides no backwards compatibility guarantees for guest binaries,
98    /// so the guest and host versions must match exactly. This might change in the future.
99    #[error(
100        "Guest binary was built with hyperlight-guest-bin {guest_bin_version}, \
101         but the host is running hyperlight {host_version}"
102    )]
103    GuestBinVersionMismatch {
104        /// Version of hyperlight-guest-bin the guest was compiled against.
105        guest_bin_version: String,
106        /// Version of hyperlight-host.
107        host_version: String,
108    },
109
110    /// A Host function was called by the guest but it was not registered.
111    #[error("HostFunction {0} was not found")]
112    HostFunctionNotFound(String),
113
114    /// Hyperlight VM error.
115    ///
116    /// **Note:** This error variant is considered internal and its structure is not stable.
117    /// It may change between versions without notice. Users should not rely on this.
118    #[doc(hidden)]
119    #[error("Internal Hyperlight VM error: {0}")]
120    HyperlightVmError(#[from] HyperlightVmError),
121
122    /// Reading Writing or Seeking data failed.
123    #[error("Reading Writing or Seeking data failed {0:?}")]
124    IOError(#[from] std::io::Error),
125
126    /// Failed to convert to Integer
127    #[error("Failed To Convert Size to usize")]
128    IntConversionFailure(#[from] TryFromIntError),
129
130    /// The flatbuffer is invalid
131    #[error("The flatbuffer is invalid")]
132    InvalidFlatBuffer(#[from] InvalidFlatbuffer),
133
134    /// Conversion of str to Json failed
135    #[error("Conversion of str data to json failed")]
136    JsonConversionFailure(#[from] serde_json::Error),
137
138    /// An attempt to get a lock from a Mutex failed.
139    #[error("Unable to lock resource")]
140    LockAttemptFailed(String),
141
142    /// Memory Access Violation at the given address. The access type and memory region flags are provided.
143    #[error("Memory Access Violation at address {0:#x} of type {1}, but memory is marked as {2}")]
144    MemoryAccessViolation(u64, MemoryRegionFlags, MemoryRegionFlags),
145
146    /// The memory request exceeds the maximum size allowed
147    #[error("Memory requested {0} exceeds maximum size allowed {1}")]
148    MemoryRequestTooBig(usize, usize),
149
150    /// The memory request is too small to contain everything that is
151    /// required
152    #[error("Memory requested {0} is less than the minimum size allowed {1}")]
153    MemoryRequestTooSmall(usize, usize),
154
155    /// Metric Not Found.
156    #[error("Metric Not Found {0:?}.")]
157    MetricNotFound(&'static str),
158
159    /// No Hypervisor was found for Sandbox.
160    #[error("No Hypervisor was found for Sandbox")]
161    NoHypervisorFound(),
162
163    /// Restore_state called with no valid snapshot
164    #[error("Restore_state called with no valid snapshot")]
165    NoMemorySnapshot,
166
167    /// Failed to get value from parameter value
168    #[error("Failed To Convert Parameter Value {0:?} to {1:?}")]
169    ParameterValueConversionFailure(ParameterValue, &'static str),
170
171    /// a failure occurred processing a PE file
172    #[error("Failure processing PE File {0:?}")]
173    PEFileProcessingFailure(#[from] goblin::error::Error),
174
175    /// The sandbox becomes **poisoned** when the guest is not run to completion, leaving it in
176    /// an inconsistent state that could compromise memory safety, data integrity, or security.
177    ///
178    /// ### When Does Poisoning Occur?
179    ///
180    /// Poisoning happens when guest execution is interrupted before normal completion:
181    ///
182    /// - **Guest panics or aborts** - When a guest function panics, crashes, or calls `abort()`,
183    ///   the normal cleanup and unwinding process is interrupted
184    /// - **Invalid memory access** - Attempts to read/write/execute memory outside allowed regions
185    /// - **Stack overflow** - Guest exhausts its stack space during execution
186    /// - **Heap exhaustion** - Guest runs out of heap memory
187    /// - **Host-initiated cancellation** - Calling [`InterruptHandle::kill()`] to forcefully
188    ///   terminate an in-progress guest function
189    ///
190    /// ## Recovery
191    ///
192    /// Use [`crate::Sandbox::restore()`] to recover from a poisoned sandbox.
193    #[error("The sandbox was poisoned")]
194    PoisonedSandbox,
195
196    /// The sandbox cannot safely perform further operations and must be discarded.
197    #[error("The sandbox is unrecoverable and must be discarded")]
198    UnrecoverableSandbox,
199
200    /// Raw pointer is less than base address
201    #[error("Raw pointer ({0:?}) was less than the base address ({1})")]
202    RawPointerLessThanBaseAddress(RawPtr, u64),
203
204    /// RefCell borrow failed
205    #[error("RefCell borrow failed")]
206    RefCellBorrowFailed(#[from] BorrowError),
207
208    /// RefCell mut borrow failed
209    #[error("RefCell mut borrow failed")]
210    RefCellMutBorrowFailed(#[from] BorrowMutError),
211
212    /// Failed to get value from return value
213    #[error("Failed To Convert Return Value {0:?} to {1:?}")]
214    ReturnValueConversionFailure(ReturnValue, &'static str),
215
216    /// Error creating or operating on memory shared with the guest
217    #[error("Failed to execute shared memory operation: {0}")]
218    SharedMemory(#[from] crate::mem::shared_mem::SharedMemoryError),
219    /// Tried to restore a snapshot into a sandbox whose registered
220    /// host functions do not satisfy the snapshot's required set.
221    #[error(
222        "Snapshot host function mismatch: missing=[{}], signature mismatches=[{}]",
223        missing.join(", "),
224        signature_mismatches.join("; ")
225    )]
226    SnapshotHostFunctionMismatch {
227        /// Functions that are required by the snapshot but not present in the target sandbox.
228        missing: Vec<String>,
229        /// Human-readable descriptions of functions whose signatures
230        /// disagree between the snapshot and the target sandbox.
231        signature_mismatches: Vec<String>,
232    },
233
234    /// SystemTimeError
235    #[error("SystemTimeError {0:?}")]
236    SystemTimeError(#[from] SystemTimeError),
237
238    /// Error occurred converting a slice to an array
239    #[error("TryFromSliceError {0:?}")]
240    TryFromSliceError(#[from] TryFromSliceError),
241
242    /// A function was called with an incorrect number of arguments
243    #[error("The number of arguments to the function is wrong: got {0:?} expected {1:?}")]
244    UnexpectedNoOfArguments(usize, usize),
245
246    /// The parameter value type is unexpected
247    #[error("The parameter value type is unexpected got {0:?} expected {1:?}")]
248    UnexpectedParameterValueType(ParameterValue, String),
249
250    /// The return value type is unexpected
251    #[error("The return value type is unexpected got {0:?} expected {1:?}")]
252    UnexpectedReturnValueType(ReturnValue, String),
253
254    /// Slice conversion to UTF8 failed
255    #[error("String Conversion of UTF8 data to str failed")]
256    UTF8StringConversionFailure(#[from] FromUtf8Error),
257
258    /// The capacity of the vector is incorrect
259    #[error(
260        "The capacity of the vector is incorrect. Capacity: {0}, Length: {1}, FlatBuffer Size: {2}"
261    )]
262    VectorCapacityIncorrect(usize, usize, i32),
263
264    /// vmm sys Error Occurred
265    #[error("vmm sys Error {0:?}")]
266    #[cfg(target_os = "linux")]
267    VmmSysError(vmm_sys_util::errno::Error),
268
269    /// Windows Error
270    #[cfg(target_os = "windows")]
271    #[error("Windows API Error Result {0:?}")]
272    WindowsAPIError(#[from] windows_result::Error),
273}
274
275impl From<Infallible> for HyperlightError {
276    fn from(_: Infallible) -> Self {
277        "Impossible as this is an infallible error".into()
278    }
279}
280
281impl From<VirtqError> for HyperlightError {
282    fn from(error: VirtqError) -> Self {
283        Self::TransportError(error.to_string())
284    }
285}
286
287impl From<&str> for HyperlightError {
288    fn from(s: &str) -> Self {
289        HyperlightError::Error(s.to_string())
290    }
291}
292
293impl<T> From<PoisonError<MutexGuard<'_, T>>> for HyperlightError {
294    // Implemented this way rather than passing the error as a source to LockAttemptFailed as that would require
295    // Box<dyn Error + Send + Sync> which is not easy to implement for PoisonError<MutexGuard<'_, T>>
296    // This is a good enough solution and allows use to use the ? operator on lock() calls
297    fn from(e: PoisonError<MutexGuard<'_, T>>) -> Self {
298        let source = match e.source() {
299            Some(s) => s.to_string(),
300            None => String::from(""),
301        };
302        HyperlightError::LockAttemptFailed(source)
303    }
304}
305
306impl HyperlightError {
307    /// Internal helper to determines if the given error has potential to poison the sandbox.
308    ///
309    /// Errors that poison the sandbox are those that can leave the sandbox in an inconsistent
310    /// state where memory, resources, or data structures may be corrupted or leaked. Usually
311    /// due to the guest not running to completion.
312    ///
313    /// If this method returns `true`, the sandbox will be poisoned and all further operations
314    /// will fail until the sandbox is restored from a non-poisoned snapshot using
315    /// [`crate::Sandbox::restore()`].
316    pub(crate) fn is_poison_error(&self) -> bool {
317        // wildcard _ or matches! not used here purposefully to ensure that new error variants
318        // are explicitly considered for poisoning behavior.
319        match self {
320            // These errors poison the sandbox because they can leave it in an inconsistent state due
321            // to the guest not running to completion.
322            HyperlightError::GuestAborted(_, _)
323            | HyperlightError::ExecutionCanceledByHost()
324            | HyperlightError::PoisonedSandbox
325            | HyperlightError::ExecutionAccessViolation(_)
326            | HyperlightError::MemoryAccessViolation(_, _, _)
327            | HyperlightError::TransportError(_)
328            // HyperlightVmError::Restore is already handled manually in restore(), but we mark it
329            // as poisoning here too for defense in depth.
330            | HyperlightError::HyperlightVmError(HyperlightVmError::Restore(_)) => true,
331
332            // These errors poison the sandbox because they can leave
333            // it in an inconsistent state due to snapshot restore
334            // failing partway through
335            HyperlightError::HyperlightVmError(HyperlightVmError::UpdateRegion(_))
336            | HyperlightError::HyperlightVmError(HyperlightVmError::AccessPageTable(_)) => true,
337
338            // HyperlightVmError::DispatchGuestCall may poison the sandbox
339            HyperlightError::HyperlightVmError(HyperlightVmError::DispatchGuestCall(e)) => {
340                e.is_poison_error()
341            }
342
343            // All other errors do not poison the sandbox.
344            HyperlightError::AnyhowError(_)
345            | HyperlightError::CheckedAddOverflow(_, _)
346            | HyperlightError::CStringConversionError(_)
347            | HyperlightError::Error(_)
348            | HyperlightError::FailedToGetValueFromParameter()
349            | HyperlightError::FieldIsMissingInGuestLogData(_)
350            | HyperlightError::GuestBinVersionMismatch { .. }
351            | HyperlightError::GuestError(_, _)
352            | HyperlightError::GuestExecutionHungOnHostFunctionCall()
353            | HyperlightError::GuestFunctionCallAlreadyInProgress()
354            | HyperlightError::GuestInterfaceUnsupportedType(_)
355            | HyperlightError::HostFunctionNotFound(_)
356            | HyperlightError::HyperlightVmError(HyperlightVmError::Create(_))
357            | HyperlightError::HyperlightVmError(HyperlightVmError::Initialize(_))
358            | HyperlightError::HyperlightVmError(HyperlightVmError::MapRegion(_))
359            | HyperlightError::HyperlightVmError(HyperlightVmError::UnmapRegion(_))
360            | HyperlightError::IOError(_)
361            | HyperlightError::IntConversionFailure(_)
362            | HyperlightError::InvalidFlatBuffer(_)
363            | HyperlightError::JsonConversionFailure(_)
364            | HyperlightError::LockAttemptFailed(_)
365            | HyperlightError::MemoryRequestTooBig(_, _)
366            | HyperlightError::MemoryRequestTooSmall(_, _)
367            | HyperlightError::MetricNotFound(_)
368            | HyperlightError::NoHypervisorFound()
369            | HyperlightError::NoMemorySnapshot
370            | HyperlightError::ParameterValueConversionFailure(_, _)
371            | HyperlightError::PEFileProcessingFailure(_)
372            | HyperlightError::RawPointerLessThanBaseAddress(_, _)
373            | HyperlightError::RefCellBorrowFailed(_)
374            | HyperlightError::RefCellMutBorrowFailed(_)
375            | HyperlightError::ReturnValueConversionFailure(_, _)
376            | HyperlightError::SnapshotHostFunctionMismatch { .. }
377            | HyperlightError::SystemTimeError(_)
378            | HyperlightError::TryFromSliceError(_)
379            | HyperlightError::UnexpectedNoOfArguments(_, _)
380            | HyperlightError::UnexpectedParameterValueType(_, _)
381            | HyperlightError::UnexpectedReturnValueType(_, _)
382            | HyperlightError::UnrecoverableSandbox
383            | HyperlightError::UTF8StringConversionFailure(_)
384            | HyperlightError::VectorCapacityIncorrect(_, _, _)
385            | HyperlightError::SharedMemory(_) => false,
386
387            #[cfg(target_os = "windows")]
388            HyperlightError::CrossBeamReceiveError(_) => false,
389            #[cfg(target_os = "windows")]
390            HyperlightError::CrossBeamSendError(_) => false,
391            #[cfg(target_os = "windows")]
392            HyperlightError::WindowsAPIError(_) => false,
393            #[cfg(target_os = "linux")]
394            HyperlightError::VmmSysError(_) => false,
395        }
396    }
397}
398
399/// Creates a `HyperlightError::Error` from a string literal or format string
400#[macro_export]
401macro_rules! new_error {
402    ($msg:literal $(,)?) => {{
403        let __args = std::format_args!($msg);
404        let __err_msg = match __args.as_str() {
405            Some(msg) => String::from(msg),
406            None => std::format!($msg),
407        };
408        $crate::HyperlightError::Error(__err_msg)
409    }};
410    ($fmtstr:expr, $($arg:tt)*) => {{
411           let __err_msg = std::format!($fmtstr, $($arg)*);
412           $crate::error::HyperlightError::Error(__err_msg)
413    }};
414}
415
416#[cfg(test)]
417mod tests {
418    use super::*;
419    use crate::hypervisor::hyperlight_vm::{
420        DispatchGuestCallError, HandleIoError, HyperlightVmError, RunVmError,
421    };
422    use crate::sandbox::outb::HandleOutbError;
423
424    #[test]
425    fn virtq_error_converts_to_poisoning_transport_error() {
426        let error = HyperlightError::from(VirtqError::InvalidState);
427
428        assert!(matches!(error, HyperlightError::TransportError(_)));
429        assert!(error.is_poison_error());
430    }
431
432    /// Test that ExecutionCancelledByHost promotes to HyperlightError::ExecutionCanceledByHost
433    #[test]
434    fn test_promote_execution_cancelled_by_host() {
435        let err = DispatchGuestCallError::Run(RunVmError::ExecutionCancelledByHost);
436        let (promoted, should_poison) = err.promote();
437
438        assert!(
439            should_poison,
440            "ExecutionCancelledByHost should poison the sandbox"
441        );
442        assert!(
443            matches!(promoted, HyperlightError::ExecutionCanceledByHost()),
444            "Expected HyperlightError::ExecutionCanceledByHost, got {:?}",
445            promoted
446        );
447    }
448
449    /// Test that GuestAborted promotes to HyperlightError::GuestAborted with correct values
450    #[test]
451    fn test_promote_guest_aborted() {
452        let err = DispatchGuestCallError::Run(RunVmError::HandleIo(HandleIoError::Outb(
453            HandleOutbError::GuestAborted {
454                code: 42,
455                message: "test abort".to_string(),
456            },
457        )));
458        let (promoted, should_poison) = err.promote();
459
460        assert!(should_poison, "GuestAborted should poison the sandbox");
461        match promoted {
462            HyperlightError::GuestAborted(code, msg) => {
463                assert_eq!(code, 42);
464                assert_eq!(msg, "test abort");
465            }
466            _ => panic!("Expected HyperlightError::GuestAborted, got {:?}", promoted),
467        }
468    }
469
470    /// Test that MemoryAccessViolation promotes to HyperlightError::MemoryAccessViolation
471    #[test]
472    fn test_promote_memory_access_violation() {
473        let err = DispatchGuestCallError::Run(RunVmError::MemoryAccessViolation {
474            addr: 0xDEADBEEF,
475            access_type: MemoryRegionFlags::WRITE,
476            region_flags: MemoryRegionFlags::READ,
477        });
478        let (promoted, should_poison) = err.promote();
479
480        assert!(
481            should_poison,
482            "MemoryAccessViolation should poison the sandbox"
483        );
484        match promoted {
485            HyperlightError::MemoryAccessViolation(addr, access_type, region_flags) => {
486                assert_eq!(addr, 0xDEADBEEF);
487                assert_eq!(access_type, MemoryRegionFlags::WRITE);
488                assert_eq!(region_flags, MemoryRegionFlags::READ);
489            }
490            _ => panic!(
491                "Expected HyperlightError::MemoryAccessViolation, got {:?}",
492                promoted
493            ),
494        }
495    }
496
497    /// Test that non-promoted Run errors are wrapped in HyperlightVmError
498    #[test]
499    fn test_promote_other_run_errors_wrapped() {
500        let err = DispatchGuestCallError::Run(RunVmError::MmioReadUnmapped(0x1000));
501        let (promoted, should_poison) = err.promote();
502
503        assert!(should_poison, "Run errors should poison the sandbox");
504        assert!(
505            matches!(
506                promoted,
507                HyperlightError::HyperlightVmError(HyperlightVmError::DispatchGuestCall(_))
508            ),
509            "Expected HyperlightError::HyperlightVmError, got {:?}",
510            promoted
511        );
512    }
513}