1use 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#[derive(Error, Debug)]
29pub enum HyperlightError {
30 #[error("Anyhow Error was returned: {0}")]
32 AnyhowError(#[from] anyhow::Error),
33
34 #[error("Couldn't add offset to base address. Offset: {0}, Base Address: {1}")]
36 CheckedAddOverflow(u64, u64),
37
38 #[error("{0:?}")]
40 #[cfg(target_os = "windows")]
41 CrossBeamReceiveError(#[from] RecvError),
42
43 #[error("{0:?}")]
45 #[cfg(target_os = "windows")]
46 CrossBeamSendError(#[from] SendError<HandleWrapper>),
47
48 #[error("Error converting CString {0:?}")]
50 CStringConversionError(#[from] std::ffi::NulError),
51
52 #[error("{0}")]
54 Error(String),
55
56 #[error("Virtqueue transport error: {0}")]
58 TransportError(String),
59
60 #[error("Non-executable address {0:#x} tried to be executed")]
62 ExecutionAccessViolation(u64),
63
64 #[error("Execution was cancelled by the host.")]
66 ExecutionCanceledByHost(),
67
68 #[error("Failed to get a value from flat buffer parameter")]
70 FailedToGetValueFromParameter(),
71
72 #[error("Field Name {0} not found in decoded GuestLogData")]
74 FieldIsMissingInGuestLogData(String),
75
76 #[error("Guest aborted: {0} {1}")]
78 GuestAborted(u8, String),
79
80 #[error("Guest error occurred {0:?}: {1}")]
82 GuestError(ErrorCode, String),
83
84 #[error("Guest execution hung on the execution of a host function call")]
86 GuestExecutionHungOnHostFunctionCall(),
87
88 #[error("Guest call is already in progress")]
90 GuestFunctionCallAlreadyInProgress(),
91
92 #[error("Unsupported type: {0}")]
94 GuestInterfaceUnsupportedType(String),
95
96 #[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 guest_bin_version: String,
106 host_version: String,
108 },
109
110 #[error("HostFunction {0} was not found")]
112 HostFunctionNotFound(String),
113
114 #[doc(hidden)]
119 #[error("Internal Hyperlight VM error: {0}")]
120 HyperlightVmError(#[from] HyperlightVmError),
121
122 #[error("Reading Writing or Seeking data failed {0:?}")]
124 IOError(#[from] std::io::Error),
125
126 #[error("Failed To Convert Size to usize")]
128 IntConversionFailure(#[from] TryFromIntError),
129
130 #[error("The flatbuffer is invalid")]
132 InvalidFlatBuffer(#[from] InvalidFlatbuffer),
133
134 #[error("Conversion of str data to json failed")]
136 JsonConversionFailure(#[from] serde_json::Error),
137
138 #[error("Unable to lock resource")]
140 LockAttemptFailed(String),
141
142 #[error("Memory Access Violation at address {0:#x} of type {1}, but memory is marked as {2}")]
144 MemoryAccessViolation(u64, MemoryRegionFlags, MemoryRegionFlags),
145
146 #[error("Memory requested {0} exceeds maximum size allowed {1}")]
148 MemoryRequestTooBig(usize, usize),
149
150 #[error("Memory requested {0} is less than the minimum size allowed {1}")]
153 MemoryRequestTooSmall(usize, usize),
154
155 #[error("Metric Not Found {0:?}.")]
157 MetricNotFound(&'static str),
158
159 #[error("No Hypervisor was found for Sandbox")]
161 NoHypervisorFound(),
162
163 #[error("Restore_state called with no valid snapshot")]
165 NoMemorySnapshot,
166
167 #[error("Failed To Convert Parameter Value {0:?} to {1:?}")]
169 ParameterValueConversionFailure(ParameterValue, &'static str),
170
171 #[error("Failure processing PE File {0:?}")]
173 PEFileProcessingFailure(#[from] goblin::error::Error),
174
175 #[error("The sandbox was poisoned")]
194 PoisonedSandbox,
195
196 #[error("The sandbox is unrecoverable and must be discarded")]
198 UnrecoverableSandbox,
199
200 #[error("Raw pointer ({0:?}) was less than the base address ({1})")]
202 RawPointerLessThanBaseAddress(RawPtr, u64),
203
204 #[error("RefCell borrow failed")]
206 RefCellBorrowFailed(#[from] BorrowError),
207
208 #[error("RefCell mut borrow failed")]
210 RefCellMutBorrowFailed(#[from] BorrowMutError),
211
212 #[error("Failed To Convert Return Value {0:?} to {1:?}")]
214 ReturnValueConversionFailure(ReturnValue, &'static str),
215
216 #[error("Failed to execute shared memory operation: {0}")]
218 SharedMemory(#[from] crate::mem::shared_mem::SharedMemoryError),
219 #[error(
222 "Snapshot host function mismatch: missing=[{}], signature mismatches=[{}]",
223 missing.join(", "),
224 signature_mismatches.join("; ")
225 )]
226 SnapshotHostFunctionMismatch {
227 missing: Vec<String>,
229 signature_mismatches: Vec<String>,
232 },
233
234 #[error("SystemTimeError {0:?}")]
236 SystemTimeError(#[from] SystemTimeError),
237
238 #[error("TryFromSliceError {0:?}")]
240 TryFromSliceError(#[from] TryFromSliceError),
241
242 #[error("The number of arguments to the function is wrong: got {0:?} expected {1:?}")]
244 UnexpectedNoOfArguments(usize, usize),
245
246 #[error("The parameter value type is unexpected got {0:?} expected {1:?}")]
248 UnexpectedParameterValueType(ParameterValue, String),
249
250 #[error("The return value type is unexpected got {0:?} expected {1:?}")]
252 UnexpectedReturnValueType(ReturnValue, String),
253
254 #[error("String Conversion of UTF8 data to str failed")]
256 UTF8StringConversionFailure(#[from] FromUtf8Error),
257
258 #[error(
260 "The capacity of the vector is incorrect. Capacity: {0}, Length: {1}, FlatBuffer Size: {2}"
261 )]
262 VectorCapacityIncorrect(usize, usize, i32),
263
264 #[error("vmm sys Error {0:?}")]
266 #[cfg(target_os = "linux")]
267 VmmSysError(vmm_sys_util::errno::Error),
268
269 #[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 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 pub(crate) fn is_poison_error(&self) -> bool {
317 match self {
320 HyperlightError::GuestAborted(_, _)
323 | HyperlightError::ExecutionCanceledByHost()
324 | HyperlightError::PoisonedSandbox
325 | HyperlightError::ExecutionAccessViolation(_)
326 | HyperlightError::MemoryAccessViolation(_, _, _)
327 | HyperlightError::TransportError(_)
328 | HyperlightError::HyperlightVmError(HyperlightVmError::Restore(_)) => true,
331
332 HyperlightError::HyperlightVmError(HyperlightVmError::UpdateRegion(_))
336 | HyperlightError::HyperlightVmError(HyperlightVmError::AccessPageTable(_)) => true,
337
338 HyperlightError::HyperlightVmError(HyperlightVmError::DispatchGuestCall(e)) => {
340 e.is_poison_error()
341 }
342
343 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#[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]
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]
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]
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]
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}