From 33b603ffe20b4e3e9da658adf1f7058a3869b33b Mon Sep 17 00:00:00 2001 From: danbugs Date: Fri, 2 May 2025 22:00:23 +0000 Subject: [PATCH 1/2] [common/peb,guest/host_{error, function_call},host/{mem,func}] removed host error region This region was unused. Ever since we ported our code from C# to Rust, if there's an error calling a host function, the host will just error out instead of returning to the guest, which is probably more sensible. Signed-off-by: danbugs --- src/hyperlight_common/src/mem/mod.rs | 6 - src/hyperlight_guest/src/host_error.rs | 43 ---- .../src/host_function_call.rs | 3 - src/hyperlight_guest/src/lib.rs | 1 - src/hyperlight_host/src/error.rs | 21 -- src/hyperlight_host/src/func/guest_err.rs | 14 +- src/hyperlight_host/src/mem/layout.rs | 81 +------ src/hyperlight_host/src/mem/memory_region.rs | 2 - src/hyperlight_host/src/mem/mgr.rs | 213 +----------------- 9 files changed, 9 insertions(+), 375 deletions(-) delete mode 100644 src/hyperlight_guest/src/host_error.rs diff --git a/src/hyperlight_common/src/mem/mod.rs b/src/hyperlight_common/src/mem/mod.rs index 0d523d43d..f24a757fe 100644 --- a/src/hyperlight_common/src/mem/mod.rs +++ b/src/hyperlight_common/src/mem/mod.rs @@ -28,11 +28,6 @@ pub struct HostFunctionDefinitions { pub fbHostFunctionDetails: *mut c_void, } -#[repr(C)] -pub struct HostException { - pub hostExceptionSize: u64, -} - #[repr(C)] pub struct GuestErrorData { pub guestErrorSize: u64, @@ -89,7 +84,6 @@ pub struct GuestPanicContextData { pub struct HyperlightPEB { pub security_cookie_seed: u64, pub guest_function_dispatch_ptr: u64, - pub hostException: HostException, pub guestErrorData: GuestErrorData, pub pCode: *mut c_char, pub pOutb: *mut c_void, diff --git a/src/hyperlight_guest/src/host_error.rs b/src/hyperlight_guest/src/host_error.rs deleted file mode 100644 index 048c44089..000000000 --- a/src/hyperlight_guest/src/host_error.rs +++ /dev/null @@ -1,43 +0,0 @@ -/* -Copyright 2024 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 core::ffi::c_void; -use core::slice::from_raw_parts; - -use hyperlight_common::flatbuffer_wrappers::guest_error::{ErrorCode, GuestError}; - -use crate::P_PEB; - -pub(crate) fn check_for_host_error() { - unsafe { - let peb_ptr = P_PEB.unwrap(); - let guest_error_buffer_ptr = (*peb_ptr).guestErrorData.guestErrorBuffer as *mut u8; - let guest_error_buffer_size = (*peb_ptr).guestErrorData.guestErrorSize as usize; - - let guest_error_buffer = from_raw_parts(guest_error_buffer_ptr, guest_error_buffer_size); - - if !guest_error_buffer.is_empty() { - let guest_error = GuestError::try_from(guest_error_buffer).expect("Invalid GuestError"); - if guest_error.code != ErrorCode::NoError { - (*peb_ptr).outputdata.outputDataBuffer = usize::MAX as *mut c_void; - panic!( - "Guest Error: {:?} - {}", - guest_error.code, guest_error.message - ); - } - } - } -} diff --git a/src/hyperlight_guest/src/host_function_call.rs b/src/hyperlight_guest/src/host_function_call.rs index e66bff4fd..a583cc86a 100644 --- a/src/hyperlight_guest/src/host_function_call.rs +++ b/src/hyperlight_guest/src/host_function_call.rs @@ -28,7 +28,6 @@ use hyperlight_common::flatbuffer_wrappers::util::get_flatbuffer_result; use hyperlight_common::mem::RunMode; use crate::error::{HyperlightGuestError, Result}; -use crate::host_error::check_for_host_error; use crate::shared_input_data::try_pop_shared_input_data_into; use crate::shared_output_data::push_shared_output_data; use crate::{OUTB_PTR, OUTB_PTR_WITH_CONTEXT, P_PEB, RUNNING_MODE}; @@ -102,8 +101,6 @@ pub fn outb(port: u16, value: u8) { panic!("Tried to call outb in invalid runmode"); } } - - check_for_host_error(); } } diff --git a/src/hyperlight_guest/src/lib.rs b/src/hyperlight_guest/src/lib.rs index dc1d1fa3b..105e8c190 100644 --- a/src/hyperlight_guest/src/lib.rs +++ b/src/hyperlight_guest/src/lib.rs @@ -38,7 +38,6 @@ pub mod guest_function_call; pub mod guest_function_definition; pub mod guest_function_register; -pub mod host_error; pub mod host_function_call; pub(crate) mod guest_logger; diff --git a/src/hyperlight_host/src/error.rs b/src/hyperlight_host/src/error.rs index b2ea080ce..de8c8d122 100644 --- a/src/hyperlight_host/src/error.rs +++ b/src/hyperlight_host/src/error.rs @@ -25,7 +25,6 @@ use std::cell::{BorrowError, BorrowMutError}; use std::convert::Infallible; use std::error::Error; use std::num::TryFromIntError; -use std::str::Utf8Error; use std::string::FromUtf8Error; use std::sync::{MutexGuard, PoisonError}; use std::time::SystemTimeError; @@ -87,14 +86,6 @@ pub enum HyperlightError { #[error("{0}")] Error(String), - /// Exception Data Length is incorrect - #[error("Exception Data Length is incorrect. Expected: {0}, Actual: {1}")] - ExceptionDataLengthIncorrect(i32, usize), - - /// Exception Message is too big - #[error("Exception Message is too big. Max Size: {0}, Actual: {1}")] - ExceptionMessageTooBig(usize, usize), - /// Execution violation #[error("Non-executable address {0:#x} tried to be executed")] ExecutionAccessViolation(u64), @@ -171,10 +162,6 @@ pub enum HyperlightError { #[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), - /// Error occurred in KVM Operation #[error("KVM Error {0:?}")] #[cfg(kvm)] @@ -225,10 +212,6 @@ pub enum HyperlightError { #[error("Restore_state called with no valid snapshot")] NoMemorySnapshot, - /// An error occurred handling an outb message - #[error("An error occurred handling an outb message {0:?}: {1}")] - OutBHandlingError(String, String), - /// Failed to get value from parameter value #[error("Failed To Convert Parameter Value {0:?} to {1:?}")] ParameterValueConversionFailure(ParameterValue, &'static str), @@ -292,10 +275,6 @@ pub enum HyperlightError { #[error("The return value type is unexpected got {0:?} expected {1:?}")] UnexpectedReturnValueType(ReturnValue, String), - /// Slice conversion to UTF8 failed - #[error("Slice Conversion of UTF8 data to str failed")] - UTF8SliceConversionFailure(#[from] Utf8Error), - /// Slice conversion to UTF8 failed #[error("String Conversion of UTF8 data to str failed")] UTF8StringConversionFailure(#[from] FromUtf8Error), diff --git a/src/hyperlight_host/src/func/guest_err.rs b/src/hyperlight_host/src/func/guest_err.rs index 9e67ef536..627237934 100644 --- a/src/hyperlight_host/src/func/guest_err.rs +++ b/src/hyperlight_host/src/func/guest_err.rs @@ -16,7 +16,7 @@ limitations under the License. use hyperlight_common::flatbuffer_wrappers::guest_error::ErrorCode; -use crate::error::HyperlightError::{GuestError, OutBHandlingError, StackOverflow}; +use crate::error::HyperlightError::{GuestError, StackOverflow}; use crate::mem::shared_mem::HostSharedMemory; use crate::metrics::{METRIC_GUEST_ERROR, METRIC_GUEST_ERROR_LABEL_CODE}; use crate::sandbox::mem_mgr::MemMgrWrapper; @@ -27,18 +27,6 @@ pub(crate) fn check_for_guest_error(mgr: &MemMgrWrapper) -> Re let guest_err = mgr.as_ref().get_guest_error()?; match guest_err.code { ErrorCode::NoError => Ok(()), - ErrorCode::OutbError => match mgr.as_ref().get_host_error()? { - Some(host_err) => { - metrics::counter!(METRIC_GUEST_ERROR, METRIC_GUEST_ERROR_LABEL_CODE => (guest_err.code as u64).to_string()).increment(1); - - log_then_return!(OutBHandlingError( - host_err.source.clone(), - guest_err.message.clone() - )); - } - // TODO: Not sure this is correct behavior. We should probably return error here - None => Ok(()), - }, ErrorCode::StackOverflow => { metrics::counter!(METRIC_GUEST_ERROR, METRIC_GUEST_ERROR_LABEL_CODE => (guest_err.code as u64).to_string()).increment(1); log_then_return!(StackOverflow()); diff --git a/src/hyperlight_host/src/mem/layout.rs b/src/hyperlight_host/src/mem/layout.rs index 69e1be38e..fb45e96e7 100644 --- a/src/hyperlight_host/src/mem/layout.rs +++ b/src/hyperlight_host/src/mem/layout.rs @@ -22,8 +22,8 @@ use rand::{rng, RngCore}; use tracing::{instrument, Span}; use super::memory_region::MemoryRegionType::{ - Code, GuardPage, GuestErrorData, Heap, HostExceptionData, InputData, OutputData, PageTables, - PanicContext, Peb, Stack, + Code, GuardPage, GuestErrorData, Heap, InputData, OutputData, PageTables, PanicContext, Peb, + Stack, }; use super::memory_region::{MemoryRegion, MemoryRegionFlags, MemoryRegionVecBuilder}; use super::mgr::AMOUNT_OF_MEMORY_PER_PT; @@ -47,8 +47,6 @@ use crate::{log_then_return, new_error, Result}; // +-------------------------------------------+ // | Guest Error Log | // +-------------------------------------------+ -// | Host Exception Handlers | -// +-------------------------------------------+ // | PEB Struct | (HyperlightPEB size) // +-------------------------------------------+ // | Guest Code | @@ -62,12 +60,6 @@ use crate::{log_then_return, new_error, Result}; // | PML4 | // +-------------------------------------------+ 0x0_000 -/// -/// - `HostExceptionData` - memory that contains details of any Host Exception that -/// occurred in outb function. it contains a 32 bit length following by a json -/// serialisation of any error that occurred. the length of this field is -/// `HostExceptionSize` from` `SandboxConfiguration` -/// /// - `GuestError` - contains a buffer for any guest error that occurred. /// the length of this field is `GuestErrorBufferSize` from `SandboxConfiguration` /// @@ -103,7 +95,6 @@ pub(crate) struct SandboxMemoryLayout { peb_offset: usize, peb_security_cookie_seed_offset: usize, peb_guest_dispatch_function_ptr_offset: usize, // set by guest in guest entrypoint - pub(crate) peb_host_exception_offset: usize, peb_guest_error_offset: usize, peb_code_and_outb_pointer_offset: usize, peb_runmode_offset: usize, @@ -115,7 +106,6 @@ pub(crate) struct SandboxMemoryLayout { // The following are the actual values // that are written to the PEB struct - pub(crate) host_exception_buffer_offset: usize, pub(super) guest_error_buffer_offset: usize, pub(super) input_data_buffer_offset: usize, pub(super) output_data_buffer_offset: usize, @@ -153,10 +143,6 @@ impl Debug for SandboxMemoryLayout { "Guest Dispatch Function Pointer Offset", &format_args!("{:#x}", self.peb_guest_dispatch_function_ptr_offset), ) - .field( - "Host Exception Offset", - &format_args!("{:#x}", self.peb_host_exception_offset), - ) .field( "Guest Error Offset", &format_args!("{:#x}", self.peb_guest_error_offset), @@ -185,10 +171,6 @@ impl Debug for SandboxMemoryLayout { "Guest Stack Offset", &format_args!("{:#x}", self.peb_guest_stack_data_offset), ) - .field( - "Host Exception Buffer Offset", - &format_args!("{:#x}", self.host_exception_buffer_offset), - ) .field( "Guest Error Buffer Offset", &format_args!("{:#x}", self.guest_error_buffer_offset), @@ -277,7 +259,6 @@ impl SandboxMemoryLayout { peb_offset + offset_of!(HyperlightPEB, security_cookie_seed); let peb_guest_dispatch_function_ptr_offset = peb_offset + offset_of!(HyperlightPEB, guest_function_dispatch_ptr); - let peb_host_exception_offset = peb_offset + offset_of!(HyperlightPEB, hostException); let peb_guest_error_offset = peb_offset + offset_of!(HyperlightPEB, guestErrorData); let peb_code_and_outb_pointer_offset = peb_offset + offset_of!(HyperlightPEB, pCode); let peb_runmode_offset = peb_offset + offset_of!(HyperlightPEB, runMode); @@ -291,13 +272,8 @@ impl SandboxMemoryLayout { // The following offsets are the actual values that relate to memory layout, // which are written to PEB struct let peb_address = Self::BASE_ADDRESS + peb_offset; - // make sure host exception buffer starts at 4K boundary - let host_exception_buffer_offset = round_up_to( - peb_guest_stack_data_offset + size_of::(), - PAGE_SIZE_USIZE, - ); let guest_error_buffer_offset = round_up_to( - host_exception_buffer_offset + cfg.get_host_exception_size(), + peb_guest_stack_data_offset + size_of::(), PAGE_SIZE_USIZE, ); let input_data_buffer_offset = round_up_to( @@ -329,7 +305,6 @@ impl SandboxMemoryLayout { heap_size, peb_security_cookie_seed_offset, peb_guest_dispatch_function_ptr_offset, - peb_host_exception_offset, peb_guest_error_offset, peb_code_and_outb_pointer_offset, peb_runmode_offset, @@ -341,7 +316,6 @@ impl SandboxMemoryLayout { guest_error_buffer_offset, sandbox_memory_config: cfg, code_size, - host_exception_buffer_offset, input_data_buffer_offset, output_data_buffer_offset, guest_heap_buffer_offset, @@ -359,14 +333,6 @@ impl SandboxMemoryLayout { self.peb_runmode_offset } - /// Get the offset in guest memory to the size field in the - /// `HostExceptionData` structure. - #[instrument(skip_all, parent = Span::current(), level= "Trace")] - pub(super) fn get_host_exception_size_offset(&self) -> usize { - // The size field is the first field in the `HostExceptionData` struct - self.peb_host_exception_offset - } - /// Get the offset in guest memory to the max size of the guest error buffer #[instrument(skip_all, parent = Span::current(), level= "Trace")] pub(super) fn get_guest_error_buffer_size_offset(&self) -> usize { @@ -398,12 +364,6 @@ impl SandboxMemoryLayout { self.stack_size } - /// Get the offset in guest memory to the start of host errors - #[instrument(skip_all, parent = Span::current(), level= "Trace")] - pub(super) fn get_host_exception_offset(&self) -> usize { - self.host_exception_buffer_offset - } - /// Get the offset in guest memory to the OutB pointer. #[instrument(skip_all, parent = Span::current(), level= "Trace")] pub(super) fn get_outb_pointer_offset(&self) -> usize { @@ -582,7 +542,6 @@ impl SandboxMemoryLayout { let mut total_mapped_memory_size: usize = round_up_to(code_size, PAGE_SIZE_USIZE); total_mapped_memory_size += round_up_to(stack_size, PAGE_SIZE_USIZE); total_mapped_memory_size += round_up_to(heap_size, PAGE_SIZE_USIZE); - total_mapped_memory_size += round_up_to(cfg.get_host_exception_size(), PAGE_SIZE_USIZE); total_mapped_memory_size += round_up_to(cfg.get_guest_error_buffer_size(), PAGE_SIZE_USIZE); total_mapped_memory_size += round_up_to(cfg.get_input_data_size(), PAGE_SIZE_USIZE); total_mapped_memory_size += round_up_to(cfg.get_output_data_size(), PAGE_SIZE_USIZE); @@ -667,36 +626,18 @@ impl SandboxMemoryLayout { } // PEB - let host_exception_offset = builder.push_page_aligned( + let guest_error_offset = builder.push_page_aligned( size_of::(), MemoryRegionFlags::READ | MemoryRegionFlags::WRITE, Peb, ); - let expected_host_exception_offset = - TryInto::::try_into(self.host_exception_buffer_offset)?; - - if host_exception_offset != expected_host_exception_offset { - return Err(new_error!( - "Host Exception offset does not match expected Host Exception offset expected: {}, actual: {}", - expected_host_exception_offset, - host_exception_offset - )); - } - - // host exception - let guest_error_offset = builder.push_page_aligned( - self.sandbox_memory_config.get_host_exception_size(), - MemoryRegionFlags::READ | MemoryRegionFlags::WRITE, - HostExceptionData, - ); - let expected_guest_error_offset = TryInto::::try_into(self.guest_error_buffer_offset)?; if guest_error_offset != expected_guest_error_offset { return Err(new_error!( - "Guest Error offset does not match expected Guest Error offset expected: {}, actual: {}", + "Guest error offset does not match expected Guest error offset expected: {}, actual: {}", expected_guest_error_offset, guest_error_offset )); @@ -877,16 +818,6 @@ impl SandboxMemoryLayout { // Skip guest_dispatch_function_ptr_offset because it is set by the guest - // Set up Host Exception Header - // The peb only needs to include the size, not the actual buffer - // since the the guest wouldn't want to read the buffer anyway - shared_mem.write_u64( - self.get_host_exception_size_offset(), - self.sandbox_memory_config - .get_host_exception_size() - .try_into()?, - )?; - // Set up Guest Error Fields let addr = get_address!(guest_error_buffer); shared_mem.write_u64(self.get_guest_error_buffer_pointer_offset(), addr)?; @@ -1027,8 +958,6 @@ mod tests { expected_size += round_up_to(size_of::(), PAGE_SIZE_USIZE); - expected_size += round_up_to(cfg.get_host_exception_size(), PAGE_SIZE_USIZE); - expected_size += round_up_to(cfg.get_guest_error_buffer_size(), PAGE_SIZE_USIZE); expected_size += round_up_to(cfg.get_input_data_size(), PAGE_SIZE_USIZE); diff --git a/src/hyperlight_host/src/mem/memory_region.rs b/src/hyperlight_host/src/mem/memory_region.rs index 6ad40ca20..638ed6655 100644 --- a/src/hyperlight_host/src/mem/memory_region.rs +++ b/src/hyperlight_host/src/mem/memory_region.rs @@ -131,8 +131,6 @@ pub enum MemoryRegionType { Code, /// The region contains the PEB Peb, - /// The region contains the Host Exception Data - HostExceptionData, /// The region contains the Guest Error Data GuestErrorData, /// The region contains the Input Data diff --git a/src/hyperlight_host/src/mem/mgr.rs b/src/hyperlight_host/src/mem/mgr.rs index e1d9a9275..e172b2018 100644 --- a/src/hyperlight_host/src/mem/mgr.rs +++ b/src/hyperlight_host/src/mem/mgr.rs @@ -14,18 +14,15 @@ See the License for the specific language governing permissions and limitations under the License. */ -use core::mem::size_of; use std::cmp::Ordering; -use std::str::from_utf8; use std::sync::{Arc, Mutex}; use hyperlight_common::flatbuffer_wrappers::function_call::{ validate_guest_function_call_buffer, FunctionCall, }; use hyperlight_common::flatbuffer_wrappers::function_types::ReturnValue; -use hyperlight_common::flatbuffer_wrappers::guest_error::{ErrorCode, GuestError}; +use hyperlight_common::flatbuffer_wrappers::guest_error::GuestError; use hyperlight_common::flatbuffer_wrappers::guest_log_data::GuestLogData; -use serde_json::from_str; use tracing::{instrument, Span}; use super::exe::ExeInfo; @@ -37,11 +34,7 @@ use super::ptr::{GuestPtr, RawPtr}; use super::ptr_offset::Offset; use super::shared_mem::{ExclusiveSharedMemory, GuestSharedMemory, HostSharedMemory, SharedMemory}; use super::shared_mem_snapshot::SharedMemorySnapshot; -use crate::error::HyperlightError::{ - ExceptionDataLengthIncorrect, ExceptionMessageTooBig, JsonConversionFailure, NoMemorySnapshot, - UTF8SliceConversionFailure, -}; -use crate::error::HyperlightHostError; +use crate::error::HyperlightError::NoMemorySnapshot; use crate::sandbox::SandboxConfiguration; use crate::{log_then_return, new_error, HyperlightError, Result}; @@ -207,8 +200,6 @@ where MemoryRegionType::Peb => PAGE_PRESENT | PAGE_RW | PAGE_NX, MemoryRegionType::PanicContext => PAGE_PRESENT | PAGE_RW | PAGE_NX, MemoryRegionType::GuestErrorData => PAGE_PRESENT | PAGE_RW | PAGE_NX, - // Host Exception Data are readonly in the guest - MemoryRegionType::HostExceptionData => PAGE_PRESENT | PAGE_NX, MemoryRegionType::PageTables => PAGE_PRESENT | PAGE_RW | PAGE_NX, }, // If there is an error then the address isn't mapped so mark it as not present @@ -598,73 +589,6 @@ impl SandboxMemoryManager { ) } - /// Get the length of the host exception - #[instrument(err(Debug), skip_all, parent = Span::current(), level= "Trace")] - fn get_host_error_length(&self) -> Result { - let offset = self.layout.get_host_exception_offset(); - // The host exception field is expected to contain a 32-bit length followed by the exception data. - self.shared_mem.read::(offset) - } - - /// Get a bool indicating if there is a host error - #[instrument(err(Debug), skip_all, parent = Span::current(), level= "Trace")] - fn has_host_error(&self) -> Result { - let offset = self.layout.get_host_exception_offset(); - // The host exception field is expected to contain a 32-bit length followed by the exception data. - let len = self.shared_mem.read::(offset)?; - Ok(len != 0) - } - - /// Get the error data that was written by the Hyperlight Host - /// Returns a `Result` containing 'Unit' or an error.Error - /// Writes the exception data to the buffer at `exception_data_ptr`. - /// - /// TODO: have this function return a Vec instead of requiring - /// the user pass in a slice of the same length as returned by - /// self.get_host_error_length() - #[instrument(err(Debug), skip_all, parent = Span::current(), level= "Trace")] - fn get_host_error_data(&self, exception_data_slc: &mut [u8]) -> Result<()> { - let offset = self.layout.get_host_exception_offset(); - let len = self.get_host_error_length()?; - - let exception_data_slc_len = exception_data_slc.len(); - if exception_data_slc_len != len as usize { - log_then_return!(ExceptionDataLengthIncorrect(len, exception_data_slc_len)); - } - // The host exception field is expected to contain a 32-bit length followed by the exception data. - self.shared_mem - .copy_to_slice(exception_data_slc, offset + size_of::())?; - Ok(()) - } - - /// Look for a `HyperlightError` generated by the host, and return - /// an `Ok(Some(the_error))` if we succeeded in looking for one, and - /// it was found. Return `Ok(None)` if we succeeded in looking for - /// one and it wasn't found. Return an `Err` if we did not succeed - /// in looking for one. - #[instrument(err(Debug), skip_all, parent = Span::current(), level= "Trace")] - pub(crate) fn get_host_error(&self) -> Result> { - if self.has_host_error()? { - let host_err_len = { - let len_i32 = self.get_host_error_length()?; - usize::try_from(len_i32) - }?; - // create a Vec of length host_err_len. - // it's important we set the length, rather than just - // the capacity, because self.get_host_error_data ensures - // the length of the vec matches the return value of - // self.get_host_error_length() - let mut host_err_data: Vec = vec![0; host_err_len]; - self.get_host_error_data(&mut host_err_data)?; - let host_err_json = from_utf8(&host_err_data).map_err(UTF8SliceConversionFailure)?; - let host_err: HyperlightHostError = - from_str(host_err_json).map_err(JsonConversionFailure)?; - Ok(Some(host_err)) - } else { - Ok(None) - } - } - /// Get the guest error data #[instrument(err(Debug), skip_all, parent = Span::current(), level= "Trace")] pub(crate) fn get_guest_error(&self) -> Result { @@ -685,58 +609,6 @@ impl SandboxMemoryManager { }) } - /// This function writes an error to guest memory and is intended to be - /// used when the host's outb handler code raises an error. - #[instrument(err(Debug), skip_all, parent = Span::current(), level= "Trace")] - fn write_outb_error( - &mut self, - guest_error_msg: &[u8], - host_exception_data: &[u8], - ) -> Result<()> { - let message = String::from_utf8(guest_error_msg.to_owned())?; - let ge = GuestError::new(ErrorCode::OutbError, message); - - let guest_error_buffer: Vec = (&ge) - .try_into() - .map_err(|_| new_error!("write_outb_error: failed to convert GuestError to Vec"))?; - - let err_buffer_size_offset = self.layout.get_guest_error_buffer_size_offset(); - let max_err_buffer_size = self.shared_mem.read::(err_buffer_size_offset)?; - - if guest_error_buffer.len() as u64 > max_err_buffer_size { - log_then_return!("The guest error message is too large to fit in the shared memory"); - } - self.shared_mem.copy_from_slice( - guest_error_buffer.as_slice(), - self.layout.guest_error_buffer_offset, - )?; - - let host_exception_offset = self.layout.get_host_exception_offset(); - let host_exception_size_offset = self.layout.get_host_exception_size_offset(); - let max_host_exception_size = { - let size_u64 = self.shared_mem.read::(host_exception_size_offset)?; - usize::try_from(size_u64) - }?; - - // First four bytes of host exception are length - - if host_exception_data.len() > max_host_exception_size - size_of::() { - log_then_return!(ExceptionMessageTooBig( - host_exception_data.len(), - max_host_exception_size - size_of::() - )); - } - - self.shared_mem - .write::(host_exception_offset, host_exception_data.len() as i32)?; - self.shared_mem.copy_from_slice( - host_exception_data, - host_exception_offset + size_of::(), - )?; - - Ok(()) - } - /// Read guest panic data from the `SharedMemory` contained within `self` #[instrument(err(Debug), skip_all, parent = Span::current(), level= "Trace")] pub fn read_guest_panic_context_data(&self) -> Result> { @@ -757,17 +629,12 @@ impl SandboxMemoryManager { #[cfg(test)] mod tests { use hyperlight_testing::rust_guest_as_pathbuf; - use serde_json::to_string; #[cfg(all(target_os = "windows", inprocess))] use serial_test::serial; - use super::SandboxMemoryManager; - use crate::error::HyperlightHostError; use crate::mem::exe::ExeInfo; - use crate::mem::layout::SandboxMemoryLayout; use crate::mem::ptr::RawPtr; - use crate::mem::ptr_offset::Offset; - use crate::mem::shared_mem::{ExclusiveSharedMemory, SharedMemory}; + use crate::mem::shared_mem::SharedMemory; use crate::sandbox::SandboxConfiguration; use crate::testing::bytes_for_path; @@ -837,78 +704,4 @@ mod tests { } } } - - /// Don't write a host error, try to read it back, and verify we - /// successfully do the read but get no error back - #[test] - fn get_host_error_none() { - let cfg = SandboxConfiguration::default(); - let layout = SandboxMemoryLayout::new(cfg, 0x10000, 0x10000, 0x10000).unwrap(); - let mut eshm = ExclusiveSharedMemory::new(layout.get_memory_size().unwrap()).unwrap(); - let mem_size = eshm.mem_size(); - layout - .write( - &mut eshm, - SandboxMemoryLayout::BASE_ADDRESS, - mem_size, - false, - ) - .unwrap(); - let emgr = SandboxMemoryManager::new( - layout, - eshm, - false, - RawPtr::from(0), - Offset::from(0), - #[cfg(target_os = "windows")] - None, - ); - let (hmgr, _) = emgr.build(); - assert_eq!(None, hmgr.get_host_error().unwrap()); - } - - /// write a host error to shared memory, then try to read it back out - #[test] - fn round_trip_host_error() { - let cfg = SandboxConfiguration::default(); - let layout = SandboxMemoryLayout::new(cfg, 0x10000, 0x10000, 0x10000).unwrap(); - let mem_size = layout.get_memory_size().unwrap(); - // write a host error and then try to read it back - let mut eshm = ExclusiveSharedMemory::new(mem_size).unwrap(); - layout - .write( - &mut eshm, - SandboxMemoryLayout::BASE_ADDRESS, - mem_size, - false, - ) - .unwrap(); - let emgr = SandboxMemoryManager::new( - layout, - eshm, - false, - RawPtr::from(0), - Offset::from(0), - #[cfg(target_os = "windows")] - None, - ); - let (mut hmgr, _) = emgr.build(); - let err = HyperlightHostError { - message: "test message".to_string(), - source: "rust test".to_string(), - }; - let err_json_bytes = { - let str = to_string(&err).unwrap(); - str.into_bytes() - }; - let err_json_msg = "test error message".to_string().into_bytes(); - hmgr.write_outb_error(&err_json_msg, &err_json_bytes) - .unwrap(); - - let host_err_opt = hmgr - .get_host_error() - .expect("get_host_err should return an Ok"); - assert!(host_err_opt.is_some()); - assert_eq!(err, host_err_opt.unwrap()); - } } From d1a90c15e166b48d5f953830ac20874dc7b71bda Mon Sep 17 00:00:00 2001 From: danbugs Date: Fri, 2 May 2025 22:29:17 +0000 Subject: [PATCH 2/2] [host/Cargo.toml] removed some unused dependencies from host's Cargo.toml - serde* - lazy_static I also removed HyperlightHostError, which is now unused. Signed-off-by: danbugs --- Cargo.lock | 20 -------------------- src/hyperlight_host/Cargo.toml | 6 ++---- src/hyperlight_host/src/error.rs | 12 ------------ 3 files changed, 2 insertions(+), 36 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index d7f2f3dfa..c4c306a35 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1239,7 +1239,6 @@ dependencies = [ "seccompiler", "serde", "serde_json", - "serde_yaml", "serial_test", "sha256", "signal-hook-registry", @@ -2876,19 +2875,6 @@ dependencies = [ "serde", ] -[[package]] -name = "serde_yaml" -version = "0.9.34+deprecated" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6a8b1a1a2ebf674015cc02edccce75287f1a0130d394307b36743c2f5d504b47" -dependencies = [ - "indexmap 2.9.0", - "itoa", - "ryu", - "serde", - "unsafe-libyaml", -] - [[package]] name = "serial_test" version = "3.2.0" @@ -3525,12 +3511,6 @@ version = "1.0.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5a5f39404a5da50712a4c1eecf25e90dd62b613502b7e925fd4e4d19b5c96512" -[[package]] -name = "unsafe-libyaml" -version = "0.2.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "673aac59facbab8a9007c7f6108d11f63b603f7cabff99fabf650fea5c32b861" - [[package]] name = "untrusted" version = "0.9.0" diff --git a/src/hyperlight_host/Cargo.toml b/src/hyperlight_host/Cargo.toml index 0ebeee966..f54f2f23a 100644 --- a/src/hyperlight_host/Cargo.toml +++ b/src/hyperlight_host/Cargo.toml @@ -30,9 +30,6 @@ flatbuffers = "25.2.10" page_size = "0.6.0" termcolor = "1.2.0" bitflags = "2.9.0" -lazy_static = "1.4.0" -serde = { version = "1.0", features = ["derive"] } -serde_json = "1.0" log = "0.4.27" tracing = { version = "0.1.41", features = ["log"] } tracing-log = "0.2.0" @@ -43,7 +40,6 @@ crossbeam = "0.8.0" crossbeam-channel = "0.5.15" thiserror = "2.0.12" tempfile = { version = "3.19", optional = true } -serde_yaml = "0.9" anyhow = "1.0" metrics = "0.24.2" @@ -67,6 +63,7 @@ windows-result = "0.3" rust-embed = { version = "8.7.0", features = ["debug-embed", "include-exclude", "interpolate-folder-path"] } sha256 = "1.6.0" windows-version = "0.1" +lazy_static = "1.4.0" [target.'cfg(unix)'.dependencies] gdbstub = { version = "0.7.5", optional = true } @@ -104,6 +101,7 @@ tracing-chrome = "0.7.2" metrics-util = "0.19.1" metrics-exporter-prometheus = "0.17.0" tracing-tracy = "0.11.4" +serde_json = "1.0" [target.'cfg(windows)'.dev-dependencies] windows = { version = "0.61", features = [ diff --git a/src/hyperlight_host/src/error.rs b/src/hyperlight_host/src/error.rs index de8c8d122..58161757c 100644 --- a/src/hyperlight_host/src/error.rs +++ b/src/hyperlight_host/src/error.rs @@ -34,8 +34,6 @@ 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 serde::{Deserialize, Serialize}; -use serde_yaml; use thiserror::Error; #[cfg(target_os = "windows")] @@ -43,12 +41,6 @@ use crate::hypervisor::wrappers::HandleWrapper; use crate::mem::memory_region::MemoryRegionFlags; use crate::mem::ptr::RawPtr; -#[derive(Serialize, Deserialize, Debug, PartialEq, Eq)] -pub(crate) struct HyperlightHostError { - pub(crate) message: String, - pub(crate) source: String, -} - /// The error type for Hyperlight operations #[derive(Error, Debug)] pub enum HyperlightError { @@ -294,10 +286,6 @@ pub enum HyperlightError { #[cfg(target_os = "windows")] #[error("Windows API Error Result {0:?}")] WindowsAPIError(#[from] windows_result::Error), - - /// Conversion of str to YAML failed - #[error("Conversion of str data to yaml failed")] - YamlConversionFailure(#[from] serde_yaml::Error), } impl From for HyperlightError {