1#[cfg(mshv2)]
18extern crate mshv_ioctls2 as mshv_ioctls;
19
20#[cfg(mshv3)]
21extern crate mshv_ioctls3 as mshv_ioctls;
22
23use std::array::TryFromSliceError;
24use std::cell::{BorrowError, BorrowMutError};
25use std::convert::Infallible;
26use std::error::Error;
27use std::num::TryFromIntError;
28use std::str::Utf8Error;
29use std::string::FromUtf8Error;
30use std::sync::{MutexGuard, PoisonError};
31use std::time::SystemTimeError;
32
33#[cfg(target_os = "windows")]
34use crossbeam_channel::{RecvError, SendError};
35use flatbuffers::InvalidFlatbuffer;
36use hyperlight_common::flatbuffer_wrappers::function_types::{ParameterValue, ReturnValue};
37use hyperlight_common::flatbuffer_wrappers::guest_error::ErrorCode;
38use serde::{Deserialize, Serialize};
39use serde_yaml;
40use thiserror::Error;
41
42#[cfg(target_os = "windows")]
43use crate::hypervisor::wrappers::HandleWrapper;
44use crate::mem::memory_region::MemoryRegionFlags;
45use crate::mem::ptr::RawPtr;
46
47#[derive(Serialize, Deserialize, Debug, PartialEq, Eq)]
48pub(crate) struct HyperlightHostError {
49 pub(crate) message: String,
50 pub(crate) source: String,
51}
52
53#[derive(Error, Debug)]
55pub enum HyperlightError {
56 #[error("Anyhow Error was returned: {0}")]
58 AnyhowError(#[from] anyhow::Error),
59 #[error("Offset: {0} out of bounds, Max is: {1}")]
61 BoundsCheckFailed(u64, usize),
62
63 #[error("Couldn't add offset to base address. Offset: {0}, Base Address: {1}")]
65 CheckedAddOverflow(u64, u64),
66
67 #[error("{0:?}")]
69 #[cfg(target_os = "windows")]
70 CrossBeamReceiveError(#[from] RecvError),
71
72 #[error("{0:?}")]
74 #[cfg(target_os = "windows")]
75 CrossBeamSendError(#[from] SendError<HandleWrapper>),
76
77 #[error("Error converting CString {0:?}")]
79 CStringConversionError(#[from] std::ffi::NulError),
80
81 #[error("Seccomp filter trapped on disallowed syscall (check STDERR for offending syscall)")]
83 #[cfg(all(feature = "seccomp", target_os = "linux"))]
84 DisallowedSyscall,
85
86 #[error("{0}")]
88 Error(String),
89
90 #[error("Exception Data Length is incorrect. Expected: {0}, Actual: {1}")]
92 ExceptionDataLengthIncorrect(i32, usize),
93
94 #[error("Exception Message is too big. Max Size: {0}, Actual: {1}")]
96 ExceptionMessageTooBig(usize, usize),
97
98 #[error("Non-executable address {0:#x} tried to be executed")]
100 ExecutionAccessViolation(u64),
101
102 #[error("Execution was cancelled by the host.")]
104 ExecutionCanceledByHost(),
105
106 #[error("Failed to get a value from flat buffer parameter")]
108 FailedToGetValueFromParameter(),
109
110 #[error("Field Name {0} not found in decoded GuestLogData")]
112 FieldIsMissingInGuestLogData(String),
113
114 #[error("Guest aborted: {0} {1}")]
116 GuestAborted(u8, String),
117
118 #[error("Cannot run from guest binary when guest binary is a buffer")]
120 GuestBinaryShouldBeAFile(),
121
122 #[error("Guest error occurred {0:?}: {1}")]
124 GuestError(ErrorCode, String),
125
126 #[error("Guest execution hung on the execution of a host function call")]
128 GuestExecutionHungOnHostFunctionCall(),
129
130 #[error("Guest call is already in progress")]
132 GuestFunctionCallAlreadyInProgress(),
133
134 #[error("Unsupported type: {0}")]
136 GuestInterfaceUnsupportedType(String),
137
138 #[error("The guest offset {0} is invalid.")]
140 GuestOffsetIsInvalid(usize),
141
142 #[error("HostFunction {0} was not found")]
144 HostFunctionNotFound(String),
145
146 #[error("Communication failure with the Hypervisor Handler thread")]
150 HypervisorHandlerCommunicationFailure(),
151
152 #[error("Hypervisor Handler execution cancel attempt on a finished execution")]
156 HypervisorHandlerExecutionCancelAttemptOnFinishedExecution(),
157
158 #[error("Hypervisor Handler Message Receive Timedout")]
160 HypervisorHandlerMessageReceiveTimedout(),
161
162 #[error("Reading Writing or Seeking data failed {0:?}")]
164 IOError(#[from] std::io::Error),
165
166 #[error("Failed To Convert Size to usize")]
168 IntConversionFailure(#[from] TryFromIntError),
169
170 #[error("The flatbuffer is invalid")]
172 InvalidFlatBuffer(#[from] InvalidFlatbuffer),
173
174 #[error("Conversion of str data to json failed")]
176 JsonConversionFailure(#[from] serde_json::Error),
177
178 #[error("KVM Error {0:?}")]
180 #[cfg(kvm)]
181 KVMError(#[source] kvm_ioctls::Error),
182
183 #[error("Unable to lock resource")]
185 LockAttemptFailed(String),
186
187 #[error("Memory Access Violation at address {0:#x} of type {1}, but memory is marked as {2}")]
189 MemoryAccessViolation(u64, MemoryRegionFlags, MemoryRegionFlags),
190
191 #[error("Memory Allocation Failed with OS Error {0:?}.")]
193 MemoryAllocationFailed(Option<i32>),
194
195 #[error("Memory Protection Failed with OS Error {0:?}.")]
197 MemoryProtectionFailed(Option<i32>),
198
199 #[error("Memory requested {0} exceeds maximum size allowed {1}")]
201 MemoryRequestTooBig(usize, usize),
202
203 #[error("Metric Not Found {0:?}.")]
205 MetricNotFound(&'static str),
206
207 #[error("mmap failed with os error {0:?}")]
209 MmapFailed(Option<i32>),
210
211 #[error("mprotect failed with os error {0:?}")]
213 MprotectFailed(Option<i32>),
214
215 #[error("mshv Error {0:?}")]
217 #[cfg(mshv)]
218 MSHVError(#[from] mshv_ioctls::MshvError),
219
220 #[error("No Hypervisor was found for Sandbox")]
222 NoHypervisorFound(),
223
224 #[error("Restore_state called with no valid snapshot")]
226 NoMemorySnapshot,
227
228 #[error("An error occurred handling an outb message {0:?}: {1}")]
230 OutBHandlingError(String, String),
231
232 #[error("Failed To Convert Parameter Value {0:?} to {1:?}")]
234 ParameterValueConversionFailure(ParameterValue, &'static str),
235
236 #[error("Failure processing PE File {0:?}")]
238 PEFileProcessingFailure(#[from] goblin::error::Error),
239
240 #[error("Prometheus Error {0:?}")]
242 Prometheus(#[from] prometheus::Error),
243
244 #[error("Raw pointer ({0:?}) was less than the base address ({1})")]
246 RawPointerLessThanBaseAddress(RawPtr, u64),
247
248 #[error("RefCell borrow failed")]
250 RefCellBorrowFailed(#[from] BorrowError),
251
252 #[error("RefCell mut borrow failed")]
254 RefCellMutBorrowFailed(#[from] BorrowMutError),
255
256 #[error("Failed To Convert Return Value {0:?} to {1:?}")]
258 ReturnValueConversionFailure(ReturnValue, &'static str),
259
260 #[error("Stack overflow detected")]
262 StackOverflow(),
263
264 #[error("Backend Error with Seccomp Filter {0:?}")]
266 #[cfg(all(feature = "seccomp", target_os = "linux"))]
267 SeccompFilterBackendError(#[from] seccompiler::BackendError),
268
269 #[error("Error with Seccomp Filter {0:?}")]
271 #[cfg(all(feature = "seccomp", target_os = "linux"))]
272 SeccompFilterError(#[from] seccompiler::Error),
273
274 #[error("SystemTimeError {0:?}")]
276 SystemTimeError(#[from] SystemTimeError),
277
278 #[error("An error occurred when translating guest address: {0:?}")]
280 #[cfg(gdb)]
281 TranslateGuestAddress(u64),
282
283 #[error("TryFromSliceError {0:?}")]
285 TryFromSliceError(#[from] TryFromSliceError),
286
287 #[error("The number of arguments to the function is wrong: got {0:?} expected {1:?}")]
289 UnexpectedNoOfArguments(usize, usize),
290
291 #[error("The parameter value type is unexpected got {0:?} expected {1:?}")]
293 UnexpectedParameterValueType(ParameterValue, String),
294
295 #[error("The return value type is unexpected got {0:?} expected {1:?}")]
297 UnexpectedReturnValueType(ReturnValue, String),
298
299 #[error("Slice Conversion of UTF8 data to str failed")]
301 UTF8SliceConversionFailure(#[from] Utf8Error),
302
303 #[error("String Conversion of UTF8 data to str failed")]
305 UTF8StringConversionFailure(#[from] FromUtf8Error),
306
307 #[error(
309 "The capacity of the vector is incorrect. Capacity: {0}, Length: {1}, FlatBuffer Size: {2}"
310 )]
311 VectorCapacityIncorrect(usize, usize, i32),
312
313 #[error("vmm sys Error {0:?}")]
315 #[cfg(target_os = "linux")]
316 VmmSysError(#[from] vmm_sys_util::errno::Error),
317
318 #[cfg(target_os = "windows")]
320 #[error("Windows API Error Result {0:?}")]
321 WindowsAPIError(#[from] windows_result::Error),
322
323 #[error("Conversion of str data to yaml failed")]
325 YamlConversionFailure(#[from] serde_yaml::Error),
326}
327
328impl From<Infallible> for HyperlightError {
329 fn from(_: Infallible) -> Self {
330 "Impossible as this is an infallible error".into()
331 }
332}
333
334impl From<&str> for HyperlightError {
335 fn from(s: &str) -> Self {
336 HyperlightError::Error(s.to_string())
337 }
338}
339
340impl<T> From<PoisonError<MutexGuard<'_, T>>> for HyperlightError {
341 fn from(e: PoisonError<MutexGuard<'_, T>>) -> Self {
345 let source = match e.source() {
346 Some(s) => s.to_string(),
347 None => String::from(""),
348 };
349 HyperlightError::LockAttemptFailed(source)
350 }
351}
352
353#[macro_export]
355macro_rules! new_error {
356 ($msg:literal $(,)?) => {{
357 let __args = std::format_args!($msg);
358 let __err_msg = match __args.as_str() {
359 Some(msg) => String::from(msg),
360 None => std::format!($msg),
361 };
362 $crate::HyperlightError::Error(__err_msg)
363 }};
364 ($fmtstr:expr, $($arg:tt)*) => {{
365 let __err_msg = std::format!($fmtstr, $($arg)*);
366 $crate::error::HyperlightError::Error(__err_msg)
367 }};
368}