hyperlight-host 0.14.0

A lightweight Virtual Machine Manager that can be hosted in an application to safely run untrusted or code within a VM partition with very low latency and overhead.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
/*
Copyright 2025  The Hyperlight Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

use std::array::TryFromSliceError;
use std::cell::{BorrowError, BorrowMutError};
use std::convert::Infallible;
use std::error::Error;
use std::num::TryFromIntError;
use std::string::FromUtf8Error;
use std::sync::{MutexGuard, PoisonError};
use std::time::SystemTimeError;

#[cfg(target_os = "windows")]
use crossbeam_channel::{RecvError, SendError};
use flatbuffers::InvalidFlatbuffer;
use hyperlight_common::flatbuffer_wrappers::function_types::{ParameterValue, ReturnValue};
use hyperlight_common::flatbuffer_wrappers::guest_error::ErrorCode;
use thiserror::Error;

use crate::hypervisor::hyperlight_vm::HyperlightVmError;
#[cfg(target_os = "windows")]
use crate::hypervisor::wrappers::HandleWrapper;
use crate::mem::memory_region::MemoryRegionFlags;
use crate::mem::ptr::RawPtr;

/// The error type for Hyperlight operations
#[derive(Error, Debug)]
pub enum HyperlightError {
    /// Anyhow error
    #[error("Anyhow Error was returned: {0}")]
    AnyhowError(#[from] anyhow::Error),
    /// Memory access out of bounds
    #[error("Offset: {0} out of bounds, Max is: {1}")]
    BoundsCheckFailed(u64, usize),

    /// Checked Add Overflow
    #[error("Couldn't add offset to base address. Offset: {0}, Base Address: {1}")]
    CheckedAddOverflow(u64, u64),

    /// Cross beam channel receive error
    #[error("{0:?}")]
    #[cfg(target_os = "windows")]
    CrossBeamReceiveError(#[from] RecvError),

    /// Cross beam channel send error
    #[error("{0:?}")]
    #[cfg(target_os = "windows")]
    CrossBeamSendError(#[from] SendError<HandleWrapper>),

    /// CString conversion error
    #[error("Error converting CString {0:?}")]
    CStringConversionError(#[from] std::ffi::NulError),

    /// A generic error with a message
    #[error("{0}")]
    Error(String),

    /// Execution violation
    #[error("Non-executable address {0:#x} tried to be executed")]
    ExecutionAccessViolation(u64),

    /// Guest execution was cancelled by the host
    #[error("Execution was cancelled by the host.")]
    ExecutionCanceledByHost(),

    /// Accessing the value of a flatbuffer parameter failed
    #[error("Failed to get a value from flat buffer parameter")]
    FailedToGetValueFromParameter(),

    ///Field Name not found in decoded GuestLogData
    #[error("Field Name {0} not found in decoded GuestLogData")]
    FieldIsMissingInGuestLogData(String),

    /// Guest aborted during outb
    #[error("Guest aborted: {0} {1}")]
    GuestAborted(u8, String),

    /// Guest call resulted in error in guest
    #[error("Guest error occurred {0:?}: {1}")]
    GuestError(ErrorCode, String),

    /// An attempt to cancel guest execution failed because it is hanging on a host function call
    #[error("Guest execution hung on the execution of a host function call")]
    GuestExecutionHungOnHostFunctionCall(),

    /// Guest call already in progress
    #[error("Guest call is already in progress")]
    GuestFunctionCallAlreadyInProgress(),

    /// The given type is not supported by the guest interface.
    #[error("Unsupported type: {0}")]
    GuestInterfaceUnsupportedType(String),

    /// The guest binary was built with a different hyperlight-guest-bin version than the host expects.
    /// Hyperlight currently provides no backwards compatibility guarantees for guest binaries,
    /// so the guest and host versions must match exactly. This might change in the future.
    #[error(
        "Guest binary was built with hyperlight-guest-bin {guest_bin_version}, \
         but the host is running hyperlight {host_version}"
    )]
    GuestBinVersionMismatch {
        /// Version of hyperlight-guest-bin the guest was compiled against.
        guest_bin_version: String,
        /// Version of hyperlight-host.
        host_version: String,
    },

    /// A Host function was called by the guest but it was not registered.
    #[error("HostFunction {0} was not found")]
    HostFunctionNotFound(String),

    /// Hyperlight VM error.
    ///
    /// **Note:** This error variant is considered internal and its structure is not stable.
    /// It may change between versions without notice. Users should not rely on this.
    #[doc(hidden)]
    #[error("Internal Hyperlight VM error: {0}")]
    HyperlightVmError(#[from] HyperlightVmError),

    /// Reading Writing or Seeking data failed.
    #[error("Reading Writing or Seeking data failed {0:?}")]
    IOError(#[from] std::io::Error),

    /// Failed to convert to Integer
    #[error("Failed To Convert Size to usize")]
    IntConversionFailure(#[from] TryFromIntError),

    /// The flatbuffer is invalid
    #[error("The flatbuffer is invalid")]
    InvalidFlatBuffer(#[from] InvalidFlatbuffer),

    /// Conversion of str to Json failed
    #[error("Conversion of str data to json failed")]
    JsonConversionFailure(#[from] serde_json::Error),

    /// An attempt to get a lock from a Mutex failed.
    #[error("Unable to lock resource")]
    LockAttemptFailed(String),

    /// Memory Access Violation at the given address. The access type and memory region flags are provided.
    #[error("Memory Access Violation at address {0:#x} of type {1}, but memory is marked as {2}")]
    MemoryAccessViolation(u64, MemoryRegionFlags, MemoryRegionFlags),

    /// Memory Allocation Failed.
    #[error("Memory Allocation Failed with OS Error {0:?}.")]
    MemoryAllocationFailed(Option<i32>),

    /// Memory Protection Failed
    #[error("Memory Protection Failed with OS Error {0:?}.")]
    MemoryProtectionFailed(Option<i32>),

    /// Memory region size mismatch
    #[error("Memory region size mismatch: host size {0:?}, guest size {1:?} region {2:?}")]
    MemoryRegionSizeMismatch(usize, usize, String),

    /// The memory request exceeds the maximum size allowed
    #[error("Memory requested {0} exceeds maximum size allowed {1}")]
    MemoryRequestTooBig(usize, usize),

    /// The memory request is too small to contain everything that is
    /// required
    #[error("Memory requested {0} is less than the minimum size allowed {1}")]
    MemoryRequestTooSmall(usize, usize),

    /// Metric Not Found.
    #[error("Metric Not Found {0:?}.")]
    MetricNotFound(&'static str),

    /// mmap Failed.
    #[error("mmap failed with os error {0:?}")]
    MmapFailed(Option<i32>),

    /// mprotect Failed.
    #[error("mprotect failed with os error {0:?}")]
    MprotectFailed(Option<i32>),

    /// No Hypervisor was found for Sandbox.
    #[error("No Hypervisor was found for Sandbox")]
    NoHypervisorFound(),

    /// Restore_state called with no valid snapshot
    #[error("Restore_state called with no valid snapshot")]
    NoMemorySnapshot,

    /// Failed to get value from parameter value
    #[error("Failed To Convert Parameter Value {0:?} to {1:?}")]
    ParameterValueConversionFailure(ParameterValue, &'static str),

    /// a failure occurred processing a PE file
    #[error("Failure processing PE File {0:?}")]
    PEFileProcessingFailure(#[from] goblin::error::Error),

    /// The sandbox becomes **poisoned** when the guest is not run to completion, leaving it in
    /// an inconsistent state that could compromise memory safety, data integrity, or security.
    ///
    /// ### When Does Poisoning Occur?
    ///
    /// Poisoning happens when guest execution is interrupted before normal completion:
    ///
    /// - **Guest panics or aborts** - When a guest function panics, crashes, or calls `abort()`,
    ///   the normal cleanup and unwinding process is interrupted
    /// - **Invalid memory access** - Attempts to read/write/execute memory outside allowed regions
    /// - **Stack overflow** - Guest exhausts its stack space during execution
    /// - **Heap exhaustion** - Guest runs out of heap memory
    /// - **Host-initiated cancellation** - Calling [`InterruptHandle::kill()`] to forcefully
    ///   terminate an in-progress guest function
    ///
    /// ## Recovery
    ///
    /// Use [`crate::MultiUseSandbox::restore()`] to recover from a poisoned sandbox.
    #[error("The sandbox was poisoned")]
    PoisonedSandbox,

    /// Raw pointer is less than base address
    #[error("Raw pointer ({0:?}) was less than the base address ({1})")]
    RawPointerLessThanBaseAddress(RawPtr, u64),

    /// RefCell borrow failed
    #[error("RefCell borrow failed")]
    RefCellBorrowFailed(#[from] BorrowError),

    /// RefCell mut borrow failed
    #[error("RefCell mut borrow failed")]
    RefCellMutBorrowFailed(#[from] BorrowMutError),

    /// Failed to get value from return value
    #[error("Failed To Convert Return Value {0:?} to {1:?}")]
    ReturnValueConversionFailure(ReturnValue, &'static str),

    /// Tried to restore snapshot to a sandbox that is not the same as the one the snapshot was taken from
    #[error("Snapshot was taken from a different sandbox")]
    SnapshotSandboxMismatch,

    /// SystemTimeError
    #[error("SystemTimeError {0:?}")]
    SystemTimeError(#[from] SystemTimeError),

    /// Error occurred converting a slice to an array
    #[error("TryFromSliceError {0:?}")]
    TryFromSliceError(#[from] TryFromSliceError),

    /// A function was called with an incorrect number of arguments
    #[error("The number of arguments to the function is wrong: got {0:?} expected {1:?}")]
    UnexpectedNoOfArguments(usize, usize),

    /// The parameter value type is unexpected
    #[error("The parameter value type is unexpected got {0:?} expected {1:?}")]
    UnexpectedParameterValueType(ParameterValue, String),

    /// The return value type is unexpected
    #[error("The return value type is unexpected got {0:?} expected {1:?}")]
    UnexpectedReturnValueType(ReturnValue, String),

    /// Slice conversion to UTF8 failed
    #[error("String Conversion of UTF8 data to str failed")]
    UTF8StringConversionFailure(#[from] FromUtf8Error),

    /// The capacity of the vector is incorrect
    #[error(
        "The capacity of the vector is incorrect. Capacity: {0}, Length: {1}, FlatBuffer Size: {2}"
    )]
    VectorCapacityIncorrect(usize, usize, i32),

    /// vmm sys Error Occurred
    #[error("vmm sys Error {0:?}")]
    #[cfg(target_os = "linux")]
    VmmSysError(vmm_sys_util::errno::Error),

    /// Windows Error
    #[cfg(target_os = "windows")]
    #[error("Windows API Error Result {0:?}")]
    WindowsAPIError(#[from] windows_result::Error),
}

impl From<Infallible> for HyperlightError {
    fn from(_: Infallible) -> Self {
        "Impossible as this is an infallible error".into()
    }
}

impl From<&str> for HyperlightError {
    fn from(s: &str) -> Self {
        HyperlightError::Error(s.to_string())
    }
}

impl<T> From<PoisonError<MutexGuard<'_, T>>> for HyperlightError {
    // Implemented this way rather than passing the error as a source to LockAttemptFailed as that would require
    // Box<dyn Error + Send + Sync> which is not easy to implement for PoisonError<MutexGuard<'_, T>>
    // This is a good enough solution and allows use to use the ? operator on lock() calls
    fn from(e: PoisonError<MutexGuard<'_, T>>) -> Self {
        let source = match e.source() {
            Some(s) => s.to_string(),
            None => String::from(""),
        };
        HyperlightError::LockAttemptFailed(source)
    }
}

impl HyperlightError {
    /// Internal helper to determines if the given error has potential to poison the sandbox.
    ///
    /// Errors that poison the sandbox are those that can leave the sandbox in an inconsistent
    /// state where memory, resources, or data structures may be corrupted or leaked. Usually
    /// due to the guest not running to completion.
    ///
    /// If this method returns `true`, the sandbox will be poisoned and all further operations
    /// will fail until the sandbox is restored from a non-poisoned snapshot using
    /// [`crate::MultiUseSandbox::restore()`].
    pub(crate) fn is_poison_error(&self) -> bool {
        // wildcard _ or matches! not used here purposefully to ensure that new error variants
        // are explicitly considered for poisoning behavior.
        match self {
            // These errors poison the sandbox because they can leave it in an inconsistent state due
            // to the guest not running to completion.
            HyperlightError::GuestAborted(_, _)
            | HyperlightError::ExecutionCanceledByHost()
            | HyperlightError::PoisonedSandbox
            | HyperlightError::ExecutionAccessViolation(_)
            | HyperlightError::MemoryAccessViolation(_, _, _)
            | HyperlightError::MemoryRegionSizeMismatch(_, _, _)
            // HyperlightVmError::Restore is already handled manually in restore(), but we mark it
            // as poisoning here too for defense in depth.
            | HyperlightError::HyperlightVmError(HyperlightVmError::Restore(_)) => true,

            // These errors poison the sandbox because they can leave
            // it in an inconsistent state due to snapshot restore
            // failing partway through
            HyperlightError::HyperlightVmError(HyperlightVmError::UpdateRegion(_))
            | HyperlightError::HyperlightVmError(HyperlightVmError::AccessPageTable(_)) => true,

            // HyperlightVmError::DispatchGuestCall may poison the sandbox
            HyperlightError::HyperlightVmError(HyperlightVmError::DispatchGuestCall(e)) => {
                e.is_poison_error()
            }

            // All other errors do not poison the sandbox.
            HyperlightError::AnyhowError(_)
            | HyperlightError::BoundsCheckFailed(_, _)
            | HyperlightError::CheckedAddOverflow(_, _)
            | HyperlightError::CStringConversionError(_)
            | HyperlightError::Error(_)
            | HyperlightError::FailedToGetValueFromParameter()
            | HyperlightError::FieldIsMissingInGuestLogData(_)
            | HyperlightError::GuestBinVersionMismatch { .. }
            | HyperlightError::GuestError(_, _)
            | HyperlightError::GuestExecutionHungOnHostFunctionCall()
            | HyperlightError::GuestFunctionCallAlreadyInProgress()
            | HyperlightError::GuestInterfaceUnsupportedType(_)
            | HyperlightError::HostFunctionNotFound(_)
            | HyperlightError::HyperlightVmError(HyperlightVmError::Create(_))
            | HyperlightError::HyperlightVmError(HyperlightVmError::Initialize(_))
            | HyperlightError::HyperlightVmError(HyperlightVmError::MapRegion(_))
            | HyperlightError::HyperlightVmError(HyperlightVmError::UnmapRegion(_))
            | HyperlightError::IOError(_)
            | HyperlightError::IntConversionFailure(_)
            | HyperlightError::InvalidFlatBuffer(_)
            | HyperlightError::JsonConversionFailure(_)
            | HyperlightError::LockAttemptFailed(_)
            | HyperlightError::MemoryAllocationFailed(_)
            | HyperlightError::MemoryProtectionFailed(_)
            | HyperlightError::MemoryRequestTooBig(_, _)
            | HyperlightError::MemoryRequestTooSmall(_, _)
            | HyperlightError::MetricNotFound(_)
            | HyperlightError::MmapFailed(_)
            | HyperlightError::MprotectFailed(_)
            | HyperlightError::NoHypervisorFound()
            | HyperlightError::NoMemorySnapshot
            | HyperlightError::ParameterValueConversionFailure(_, _)
            | HyperlightError::PEFileProcessingFailure(_)
            | HyperlightError::RawPointerLessThanBaseAddress(_, _)
            | HyperlightError::RefCellBorrowFailed(_)
            | HyperlightError::RefCellMutBorrowFailed(_)
            | HyperlightError::ReturnValueConversionFailure(_, _)
            | HyperlightError::SnapshotSandboxMismatch
            | HyperlightError::SystemTimeError(_)
            | HyperlightError::TryFromSliceError(_)
            | HyperlightError::UnexpectedNoOfArguments(_, _)
            | HyperlightError::UnexpectedParameterValueType(_, _)
            | HyperlightError::UnexpectedReturnValueType(_, _)
            | HyperlightError::UTF8StringConversionFailure(_)
            | HyperlightError::VectorCapacityIncorrect(_, _, _) => false,

            #[cfg(target_os = "windows")]
            HyperlightError::CrossBeamReceiveError(_) => false,
            #[cfg(target_os = "windows")]
            HyperlightError::CrossBeamSendError(_) => false,
            #[cfg(target_os = "windows")]
            HyperlightError::WindowsAPIError(_) => false,
            #[cfg(target_os = "linux")]
            HyperlightError::VmmSysError(_) => false,
        }
    }
}

/// Creates a `HyperlightError::Error` from a string literal or format string
#[macro_export]
macro_rules! new_error {
    ($msg:literal $(,)?) => {{
        let __args = std::format_args!($msg);
        let __err_msg = match __args.as_str() {
            Some(msg) => String::from(msg),
            None => std::format!($msg),
        };
        $crate::HyperlightError::Error(__err_msg)
    }};
    ($fmtstr:expr, $($arg:tt)*) => {{
           let __err_msg = std::format!($fmtstr, $($arg)*);
           $crate::error::HyperlightError::Error(__err_msg)
    }};
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::hypervisor::hyperlight_vm::{
        DispatchGuestCallError, HandleIoError, HyperlightVmError, RunVmError,
    };
    use crate::sandbox::outb::HandleOutbError;

    /// Test that ExecutionCancelledByHost promotes to HyperlightError::ExecutionCanceledByHost
    #[test]
    fn test_promote_execution_cancelled_by_host() {
        let err = DispatchGuestCallError::Run(RunVmError::ExecutionCancelledByHost);
        let (promoted, should_poison) = err.promote();

        assert!(
            should_poison,
            "ExecutionCancelledByHost should poison the sandbox"
        );
        assert!(
            matches!(promoted, HyperlightError::ExecutionCanceledByHost()),
            "Expected HyperlightError::ExecutionCanceledByHost, got {:?}",
            promoted
        );
    }

    /// Test that GuestAborted promotes to HyperlightError::GuestAborted with correct values
    #[test]
    fn test_promote_guest_aborted() {
        let err = DispatchGuestCallError::Run(RunVmError::HandleIo(HandleIoError::Outb(
            HandleOutbError::GuestAborted {
                code: 42,
                message: "test abort".to_string(),
            },
        )));
        let (promoted, should_poison) = err.promote();

        assert!(should_poison, "GuestAborted should poison the sandbox");
        match promoted {
            HyperlightError::GuestAborted(code, msg) => {
                assert_eq!(code, 42);
                assert_eq!(msg, "test abort");
            }
            _ => panic!("Expected HyperlightError::GuestAborted, got {:?}", promoted),
        }
    }

    /// Test that MemoryAccessViolation promotes to HyperlightError::MemoryAccessViolation
    #[test]
    fn test_promote_memory_access_violation() {
        let err = DispatchGuestCallError::Run(RunVmError::MemoryAccessViolation {
            addr: 0xDEADBEEF,
            access_type: MemoryRegionFlags::WRITE,
            region_flags: MemoryRegionFlags::READ,
        });
        let (promoted, should_poison) = err.promote();

        assert!(
            should_poison,
            "MemoryAccessViolation should poison the sandbox"
        );
        match promoted {
            HyperlightError::MemoryAccessViolation(addr, access_type, region_flags) => {
                assert_eq!(addr, 0xDEADBEEF);
                assert_eq!(access_type, MemoryRegionFlags::WRITE);
                assert_eq!(region_flags, MemoryRegionFlags::READ);
            }
            _ => panic!(
                "Expected HyperlightError::MemoryAccessViolation, got {:?}",
                promoted
            ),
        }
    }

    /// Test that non-promoted Run errors are wrapped in HyperlightVmError
    #[test]
    fn test_promote_other_run_errors_wrapped() {
        let err = DispatchGuestCallError::Run(RunVmError::MmioReadUnmapped(0x1000));
        let (promoted, should_poison) = err.promote();

        assert!(should_poison, "Run errors should poison the sandbox");
        assert!(
            matches!(
                promoted,
                HyperlightError::HyperlightVmError(HyperlightVmError::DispatchGuestCall(_))
            ),
            "Expected HyperlightError::HyperlightVmError, got {:?}",
            promoted
        );
    }
}