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::string::FromUtf8Error;
29use std::sync::{MutexGuard, PoisonError};
30use std::time::SystemTimeError;
31
32#[cfg(target_os = "windows")]
33use crossbeam_channel::{RecvError, SendError};
34use flatbuffers::InvalidFlatbuffer;
35use hyperlight_common::flatbuffer_wrappers::function_types::{ParameterValue, ReturnValue};
36use hyperlight_common::flatbuffer_wrappers::guest_error::ErrorCode;
37use thiserror::Error;
38
39#[cfg(target_os = "windows")]
40use crate::hypervisor::wrappers::HandleWrapper;
41use crate::mem::memory_region::MemoryRegionFlags;
42use crate::mem::ptr::RawPtr;
43
44#[derive(Error, Debug)]
46pub enum HyperlightError {
47 #[error("Anyhow Error was returned: {0}")]
49 AnyhowError(#[from] anyhow::Error),
50 #[error("Offset: {0} out of bounds, Max is: {1}")]
52 BoundsCheckFailed(u64, usize),
53
54 #[error("Couldn't add offset to base address. Offset: {0}, Base Address: {1}")]
56 CheckedAddOverflow(u64, u64),
57
58 #[error("{0:?}")]
60 #[cfg(target_os = "windows")]
61 CrossBeamReceiveError(#[from] RecvError),
62
63 #[error("{0:?}")]
65 #[cfg(target_os = "windows")]
66 CrossBeamSendError(#[from] SendError<HandleWrapper>),
67
68 #[error("Error converting CString {0:?}")]
70 CStringConversionError(#[from] std::ffi::NulError),
71
72 #[error("Seccomp filter trapped on disallowed syscall (check STDERR for offending syscall)")]
74 #[cfg(all(feature = "seccomp", target_os = "linux"))]
75 DisallowedSyscall,
76
77 #[error("{0}")]
79 Error(String),
80
81 #[error("Non-executable address {0:#x} tried to be executed")]
83 ExecutionAccessViolation(u64),
84
85 #[error("Execution was cancelled by the host.")]
87 ExecutionCanceledByHost(),
88
89 #[error("Failed to get a value from flat buffer parameter")]
91 FailedToGetValueFromParameter(),
92
93 #[error("Field Name {0} not found in decoded GuestLogData")]
95 FieldIsMissingInGuestLogData(String),
96
97 #[error("Guest aborted: {0} {1}")]
99 GuestAborted(u8, String),
100
101 #[error("Guest error occurred {0:?}: {1}")]
103 GuestError(ErrorCode, String),
104
105 #[error("Guest execution hung on the execution of a host function call")]
107 GuestExecutionHungOnHostFunctionCall(),
108
109 #[error("Guest call is already in progress")]
111 GuestFunctionCallAlreadyInProgress(),
112
113 #[error("Unsupported type: {0}")]
115 GuestInterfaceUnsupportedType(String),
116
117 #[error("The guest offset {0} is invalid.")]
119 GuestOffsetIsInvalid(usize),
120
121 #[error("HostFunction {0} was not found")]
123 HostFunctionNotFound(String),
124
125 #[error("Communication failure with the Hypervisor Handler thread")]
129 HypervisorHandlerCommunicationFailure(),
130
131 #[error("Hypervisor Handler execution cancel attempt on a finished execution")]
135 HypervisorHandlerExecutionCancelAttemptOnFinishedExecution(),
136
137 #[error("Hypervisor Handler Message Receive Timedout")]
139 HypervisorHandlerMessageReceiveTimedout(),
140
141 #[error("Reading Writing or Seeking data failed {0:?}")]
143 IOError(#[from] std::io::Error),
144
145 #[error("Failed To Convert Size to usize")]
147 IntConversionFailure(#[from] TryFromIntError),
148
149 #[error("The flatbuffer is invalid")]
151 InvalidFlatBuffer(#[from] InvalidFlatbuffer),
152
153 #[error("KVM Error {0:?}")]
155 #[cfg(kvm)]
156 KVMError(#[from] kvm_ioctls::Error),
157
158 #[error("Conversion of str data to json failed")]
160 JsonConversionFailure(#[from] serde_json::Error),
161
162 #[error("Unable to lock resource")]
164 LockAttemptFailed(String),
165
166 #[error("Memory Access Violation at address {0:#x} of type {1}, but memory is marked as {2}")]
168 MemoryAccessViolation(u64, MemoryRegionFlags, MemoryRegionFlags),
169
170 #[error("Memory Allocation Failed with OS Error {0:?}.")]
172 MemoryAllocationFailed(Option<i32>),
173
174 #[error("Memory Protection Failed with OS Error {0:?}.")]
176 MemoryProtectionFailed(Option<i32>),
177
178 #[error("Memory requested {0} exceeds maximum size allowed {1}")]
180 MemoryRequestTooBig(usize, usize),
181
182 #[error("Metric Not Found {0:?}.")]
184 MetricNotFound(&'static str),
185
186 #[error("mmap failed with os error {0:?}")]
188 MmapFailed(Option<i32>),
189
190 #[error("mprotect failed with os error {0:?}")]
192 MprotectFailed(Option<i32>),
193
194 #[error("mshv Error {0:?}")]
196 #[cfg(mshv)]
197 MSHVError(#[from] mshv_ioctls::MshvError),
198
199 #[error("No Hypervisor was found for Sandbox")]
201 NoHypervisorFound(),
202
203 #[error("Restore_state called with no valid snapshot")]
205 NoMemorySnapshot,
206
207 #[error("Failed To Convert Parameter Value {0:?} to {1:?}")]
209 ParameterValueConversionFailure(ParameterValue, &'static str),
210
211 #[error("Failure processing PE File {0:?}")]
213 PEFileProcessingFailure(#[from] goblin::error::Error),
214
215 #[error("Raw pointer ({0:?}) was less than the base address ({1})")]
217 RawPointerLessThanBaseAddress(RawPtr, u64),
218
219 #[error("RefCell borrow failed")]
221 RefCellBorrowFailed(#[from] BorrowError),
222
223 #[error("RefCell mut borrow failed")]
225 RefCellMutBorrowFailed(#[from] BorrowMutError),
226
227 #[error("Failed To Convert Return Value {0:?} to {1:?}")]
229 ReturnValueConversionFailure(ReturnValue, &'static str),
230
231 #[error("Stack overflow detected")]
233 StackOverflow(),
234
235 #[error("Backend Error with Seccomp Filter {0:?}")]
237 #[cfg(all(feature = "seccomp", target_os = "linux"))]
238 SeccompFilterBackendError(#[from] seccompiler::BackendError),
239
240 #[error("Error with Seccomp Filter {0:?}")]
242 #[cfg(all(feature = "seccomp", target_os = "linux"))]
243 SeccompFilterError(#[from] seccompiler::Error),
244
245 #[error("SystemTimeError {0:?}")]
247 SystemTimeError(#[from] SystemTimeError),
248
249 #[error("An error occurred when translating guest address: {0:?}")]
251 #[cfg(gdb)]
252 TranslateGuestAddress(u64),
253
254 #[error("TryFromSliceError {0:?}")]
256 TryFromSliceError(#[from] TryFromSliceError),
257
258 #[error("The number of arguments to the function is wrong: got {0:?} expected {1:?}")]
260 UnexpectedNoOfArguments(usize, usize),
261
262 #[error("The parameter value type is unexpected got {0:?} expected {1:?}")]
264 UnexpectedParameterValueType(ParameterValue, String),
265
266 #[error("The return value type is unexpected got {0:?} expected {1:?}")]
268 UnexpectedReturnValueType(ReturnValue, String),
269
270 #[error("String Conversion of UTF8 data to str failed")]
272 UTF8StringConversionFailure(#[from] FromUtf8Error),
273
274 #[error(
276 "The capacity of the vector is incorrect. Capacity: {0}, Length: {1}, FlatBuffer Size: {2}"
277 )]
278 VectorCapacityIncorrect(usize, usize, i32),
279
280 #[error("vmm sys Error {0:?}")]
282 #[cfg(target_os = "linux")]
283 VmmSysError(#[from] vmm_sys_util::errno::Error),
284
285 #[cfg(target_os = "windows")]
287 #[error("Windows API Error Result {0:?}")]
288 WindowsAPIError(#[from] windows_result::Error),
289}
290
291impl From<Infallible> for HyperlightError {
292 fn from(_: Infallible) -> Self {
293 "Impossible as this is an infallible error".into()
294 }
295}
296
297impl From<&str> for HyperlightError {
298 fn from(s: &str) -> Self {
299 HyperlightError::Error(s.to_string())
300 }
301}
302
303impl<T> From<PoisonError<MutexGuard<'_, T>>> for HyperlightError {
304 fn from(e: PoisonError<MutexGuard<'_, T>>) -> Self {
308 let source = match e.source() {
309 Some(s) => s.to_string(),
310 None => String::from(""),
311 };
312 HyperlightError::LockAttemptFailed(source)
313 }
314}
315
316#[macro_export]
318macro_rules! new_error {
319 ($msg:literal $(,)?) => {{
320 let __args = std::format_args!($msg);
321 let __err_msg = match __args.as_str() {
322 Some(msg) => String::from(msg),
323 None => std::format!($msg),
324 };
325 $crate::HyperlightError::Error(__err_msg)
326 }};
327 ($fmtstr:expr, $($arg:tt)*) => {{
328 let __err_msg = std::format!($fmtstr, $($arg)*);
329 $crate::error::HyperlightError::Error(__err_msg)
330 }};
331}