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(#[from] 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("Raw pointer ({0:?}) was less than the base address ({1})")]
242 RawPointerLessThanBaseAddress(RawPtr, u64),
243
244 #[error("RefCell borrow failed")]
246 RefCellBorrowFailed(#[from] BorrowError),
247
248 #[error("RefCell mut borrow failed")]
250 RefCellMutBorrowFailed(#[from] BorrowMutError),
251
252 #[error("Failed To Convert Return Value {0:?} to {1:?}")]
254 ReturnValueConversionFailure(ReturnValue, &'static str),
255
256 #[error("Stack overflow detected")]
258 StackOverflow(),
259
260 #[error("Backend Error with Seccomp Filter {0:?}")]
262 #[cfg(all(feature = "seccomp", target_os = "linux"))]
263 SeccompFilterBackendError(#[from] seccompiler::BackendError),
264
265 #[error("Error with Seccomp Filter {0:?}")]
267 #[cfg(all(feature = "seccomp", target_os = "linux"))]
268 SeccompFilterError(#[from] seccompiler::Error),
269
270 #[error("SystemTimeError {0:?}")]
272 SystemTimeError(#[from] SystemTimeError),
273
274 #[error("An error occurred when translating guest address: {0:?}")]
276 #[cfg(gdb)]
277 TranslateGuestAddress(u64),
278
279 #[error("TryFromSliceError {0:?}")]
281 TryFromSliceError(#[from] TryFromSliceError),
282
283 #[error("The number of arguments to the function is wrong: got {0:?} expected {1:?}")]
285 UnexpectedNoOfArguments(usize, usize),
286
287 #[error("The parameter value type is unexpected got {0:?} expected {1:?}")]
289 UnexpectedParameterValueType(ParameterValue, String),
290
291 #[error("The return value type is unexpected got {0:?} expected {1:?}")]
293 UnexpectedReturnValueType(ReturnValue, String),
294
295 #[error("Slice Conversion of UTF8 data to str failed")]
297 UTF8SliceConversionFailure(#[from] Utf8Error),
298
299 #[error("String Conversion of UTF8 data to str failed")]
301 UTF8StringConversionFailure(#[from] FromUtf8Error),
302
303 #[error(
305 "The capacity of the vector is incorrect. Capacity: {0}, Length: {1}, FlatBuffer Size: {2}"
306 )]
307 VectorCapacityIncorrect(usize, usize, i32),
308
309 #[error("vmm sys Error {0:?}")]
311 #[cfg(target_os = "linux")]
312 VmmSysError(#[from] vmm_sys_util::errno::Error),
313
314 #[cfg(target_os = "windows")]
316 #[error("Windows API Error Result {0:?}")]
317 WindowsAPIError(#[from] windows_result::Error),
318
319 #[error("Conversion of str data to yaml failed")]
321 YamlConversionFailure(#[from] serde_yaml::Error),
322}
323
324impl From<Infallible> for HyperlightError {
325 fn from(_: Infallible) -> Self {
326 "Impossible as this is an infallible error".into()
327 }
328}
329
330impl From<&str> for HyperlightError {
331 fn from(s: &str) -> Self {
332 HyperlightError::Error(s.to_string())
333 }
334}
335
336impl<T> From<PoisonError<MutexGuard<'_, T>>> for HyperlightError {
337 fn from(e: PoisonError<MutexGuard<'_, T>>) -> Self {
341 let source = match e.source() {
342 Some(s) => s.to_string(),
343 None => String::from(""),
344 };
345 HyperlightError::LockAttemptFailed(source)
346 }
347}
348
349#[macro_export]
351macro_rules! new_error {
352 ($msg:literal $(,)?) => {{
353 let __args = std::format_args!($msg);
354 let __err_msg = match __args.as_str() {
355 Some(msg) => String::from(msg),
356 None => std::format!($msg),
357 };
358 $crate::HyperlightError::Error(__err_msg)
359 }};
360 ($fmtstr:expr, $($arg:tt)*) => {{
361 let __err_msg = std::format!($fmtstr, $($arg)*);
362 $crate::error::HyperlightError::Error(__err_msg)
363 }};
364}