diff --git a/.devcontainer/Dockerfile b/.devcontainer/Dockerfile index 99b93e95b..2f98aee7b 100644 --- a/.devcontainer/Dockerfile +++ b/.devcontainer/Dockerfile @@ -52,7 +52,7 @@ RUN SNIPPET="export PROMPT_COMMAND='history -a' && export HISTFILE=/commandhisto USER $USER -ARG RUST_TOOLCHAIN=1.81.0 +ARG RUST_TOOLCHAIN=1.85.0 # Install rust RUN curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y \ diff --git a/.github/workflows/Benchmarks.yml b/.github/workflows/Benchmarks.yml index 245fbf625..cfb84dda2 100644 --- a/.github/workflows/Benchmarks.yml +++ b/.github/workflows/Benchmarks.yml @@ -30,7 +30,7 @@ jobs: - uses: hyperlight-dev/ci-setup-workflow@v1.2.0 with: - rust-toolchain: "1.81.0" + rust-toolchain: "1.85.0" env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} diff --git a/.github/workflows/CargoAudit.yml b/.github/workflows/CargoAudit.yml index 015436c51..b608a29ae 100644 --- a/.github/workflows/CargoAudit.yml +++ b/.github/workflows/CargoAudit.yml @@ -19,7 +19,7 @@ jobs: # TODO: Once the runner image is updated to include the necessary tools (without downloading), we can switch to the common workflow. - uses: dtolnay/rust-toolchain@master with: - toolchain: "1.81.0" + toolchain: "1.85.0" - uses: rustsec/audit-check@v2.0.0 with: diff --git a/.github/workflows/CargoPublish.yml b/.github/workflows/CargoPublish.yml index fbeb32a77..4bd929162 100644 --- a/.github/workflows/CargoPublish.yml +++ b/.github/workflows/CargoPublish.yml @@ -34,7 +34,7 @@ jobs: - uses: hyperlight-dev/ci-setup-workflow@v1.2.0 with: - rust-toolchain: "1.81.0" + rust-toolchain: "1.85.0" - name: Check crate versions shell: bash diff --git a/.github/workflows/CreateDevcontainerImage.yml b/.github/workflows/CreateDevcontainerImage.yml index eb676ed28..74c5769ce 100644 --- a/.github/workflows/CreateDevcontainerImage.yml +++ b/.github/workflows/CreateDevcontainerImage.yml @@ -16,7 +16,7 @@ env: USER: vscode GROUP: vscode LLVM_VERSION: 17 - RUST_TOOLCHAIN_DEFAULT: 1.81.0 + RUST_TOOLCHAIN_DEFAULT: 1.85.0 RUST_TOOLCHAIN_FILE: rust-toolchain.toml # There is a single job in this workflow. It's configured to run on the latest available version of Ubuntu. diff --git a/.github/workflows/CreateRelease.yml b/.github/workflows/CreateRelease.yml index af98f8a0d..c86b8e7fd 100644 --- a/.github/workflows/CreateRelease.yml +++ b/.github/workflows/CreateRelease.yml @@ -23,7 +23,7 @@ jobs: - uses: hyperlight-dev/ci-setup-workflow@v1.2.0 with: - rust-toolchain: "1.81.0" + rust-toolchain: "1.85.0" env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} @@ -43,7 +43,7 @@ jobs: - uses: hyperlight-dev/ci-setup-workflow@v1.2.0 with: - rust-toolchain: "1.81.0" + rust-toolchain: "1.85.0" env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} @@ -105,7 +105,7 @@ jobs: - uses: hyperlight-dev/ci-setup-workflow@v1.2.0 with: - rust-toolchain: "1.81.0" + rust-toolchain: "1.85.0" env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} diff --git a/.github/workflows/dep_build_guest_binaries.yml b/.github/workflows/dep_build_guest_binaries.yml index 19fdee742..a8c0543a0 100644 --- a/.github/workflows/dep_build_guest_binaries.yml +++ b/.github/workflows/dep_build_guest_binaries.yml @@ -33,7 +33,7 @@ jobs: - uses: hyperlight-dev/ci-setup-workflow@v1.2.0 with: - rust-toolchain: "1.81.0" + rust-toolchain: "1.85.0" env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} diff --git a/.github/workflows/dep_fuzzing.yml b/.github/workflows/dep_fuzzing.yml index d9f5a7562..dea0e2208 100644 --- a/.github/workflows/dep_fuzzing.yml +++ b/.github/workflows/dep_fuzzing.yml @@ -34,7 +34,7 @@ jobs: - uses: hyperlight-dev/ci-setup-workflow@v1.2.0 with: - rust-toolchain: "1.81.0" + rust-toolchain: "1.85.0" env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} diff --git a/.github/workflows/dep_rust.yml b/.github/workflows/dep_rust.yml index 24450fe78..d678cb784 100644 --- a/.github/workflows/dep_rust.yml +++ b/.github/workflows/dep_rust.yml @@ -56,7 +56,7 @@ jobs: - uses: hyperlight-dev/ci-setup-workflow@v1.2.0 with: - rust-toolchain: "1.81.0" + rust-toolchain: "1.85.0" env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} diff --git a/Cargo.lock b/Cargo.lock index 5a575fc5e..cd9f2b4a9 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1,6 +1,6 @@ # This file is automatically @generated by Cargo. # It is not intended for manual editing. -version = 3 +version = 4 [[package]] name = "addr2line" @@ -1210,7 +1210,7 @@ dependencies = [ [[package]] name = "hyperlight-testing" -version = "0.0.0" +version = "0.2.0" dependencies = [ "anyhow", "log", @@ -1231,6 +1231,7 @@ dependencies = [ "hyperlight-common", "hyperlight-guest", "log", + "spin", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index 3fa824ad8..a2c28b670 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -25,8 +25,8 @@ exclude = [ [workspace.package] version = "0.2.0" -edition = "2021" -rust-version = "1.80.0" +edition = "2024" +rust-version = "1.85.0" license = "Apache-2.0" homepage = "https://github.com/hyperlight-dev/hyperlight" repository = "https://github.com/hyperlight-dev/hyperlight" diff --git a/fuzz/fuzz_targets/host_call.rs b/fuzz/fuzz_targets/host_call.rs index 83696cb5e..db2240c37 100644 --- a/fuzz/fuzz_targets/host_call.rs +++ b/fuzz/fuzz_targets/host_call.rs @@ -19,8 +19,8 @@ limitations under the License. use std::sync::{Mutex, OnceLock}; use hyperlight_host::func::{ParameterValue, ReturnType}; -use hyperlight_host::sandbox::uninitialized::GuestBinary; use hyperlight_host::sandbox::SandboxConfiguration; +use hyperlight_host::sandbox::uninitialized::GuestBinary; use hyperlight_host::sandbox_state::sandbox::EvolvableSandbox; use hyperlight_host::sandbox_state::transition::Noop; use hyperlight_host::{HyperlightError, MultiUseSandbox, UninitializedSandbox}; diff --git a/fuzz/fuzz_targets/host_print.rs b/fuzz/fuzz_targets/host_print.rs index 576f56eec..11bd1d368 100644 --- a/fuzz/fuzz_targets/host_print.rs +++ b/fuzz/fuzz_targets/host_print.rs @@ -8,7 +8,7 @@ use hyperlight_host::sandbox_state::sandbox::EvolvableSandbox; use hyperlight_host::sandbox_state::transition::Noop; use hyperlight_host::{MultiUseSandbox, UninitializedSandbox}; use hyperlight_testing::simple_guest_for_fuzzing_as_string; -use libfuzzer_sys::{fuzz_target, Corpus}; +use libfuzzer_sys::{Corpus, fuzz_target}; static SANDBOX: OnceLock> = OnceLock::new(); diff --git a/hack/rust-dependabot-patch.Dockerfile b/hack/rust-dependabot-patch.Dockerfile index bf305c082..3006ad09d 100644 --- a/hack/rust-dependabot-patch.Dockerfile +++ b/hack/rust-dependabot-patch.Dockerfile @@ -1,2 +1,2 @@ FROM dependabot/dependabot-script -RUN rustup toolchain install 1.81.0 && rustup default 1.81.0 +RUN rustup toolchain install 1.85.0 && rustup default 1.85.0 diff --git a/rust-toolchain.toml b/rust-toolchain.toml index 3cf2110e7..552d6d698 100644 --- a/rust-toolchain.toml +++ b/rust-toolchain.toml @@ -1,2 +1,2 @@ [toolchain] -channel = "1.81.0" \ No newline at end of file +channel = "1.85.0" \ No newline at end of file diff --git a/src/hyperlight_common/src/flatbuffer_wrappers/function_call.rs b/src/hyperlight_common/src/flatbuffer_wrappers/function_call.rs index 987fb369a..9ce71187f 100644 --- a/src/hyperlight_common/src/flatbuffer_wrappers/function_call.rs +++ b/src/hyperlight_common/src/flatbuffer_wrappers/function_call.rs @@ -17,18 +17,18 @@ limitations under the License. use alloc::string::{String, ToString}; use alloc::vec::Vec; -use anyhow::{bail, Error, Result}; -use flatbuffers::{size_prefixed_root, WIPOffset}; +use anyhow::{Error, Result, bail}; +use flatbuffers::{WIPOffset, size_prefixed_root}; #[cfg(feature = "tracing")] -use tracing::{instrument, Span}; +use tracing::{Span, instrument}; use super::function_types::{ParameterValue, ReturnType}; use crate::flatbuffers::hyperlight::generated::{ - hlbool, hlboolArgs, hldouble, hldoubleArgs, hlfloat, hlfloatArgs, hlint, hlintArgs, hllong, - hllongArgs, hlstring, hlstringArgs, hluint, hluintArgs, hlulong, hlulongArgs, hlvecbytes, - hlvecbytesArgs, FunctionCall as FbFunctionCall, FunctionCallArgs as FbFunctionCallArgs, + FunctionCall as FbFunctionCall, FunctionCallArgs as FbFunctionCallArgs, FunctionCallType as FbFunctionCallType, Parameter, ParameterArgs, - ParameterValue as FbParameterValue, + ParameterValue as FbParameterValue, hlbool, hlboolArgs, hldouble, hldoubleArgs, hlfloat, + hlfloatArgs, hlint, hlintArgs, hllong, hllongArgs, hlstring, hlstringArgs, hluint, hluintArgs, + hlulong, hlulongArgs, hlvecbytes, hlvecbytesArgs, }; /// The type of function call. diff --git a/src/hyperlight_common/src/flatbuffer_wrappers/function_types.rs b/src/hyperlight_common/src/flatbuffer_wrappers/function_types.rs index 42a26c81c..8ea05b49e 100644 --- a/src/hyperlight_common/src/flatbuffer_wrappers/function_types.rs +++ b/src/hyperlight_common/src/flatbuffer_wrappers/function_types.rs @@ -17,18 +17,18 @@ limitations under the License. use alloc::string::{String, ToString}; use alloc::vec::Vec; -use anyhow::{anyhow, bail, Error, Result}; +use anyhow::{Error, Result, anyhow, bail}; use flatbuffers::size_prefixed_root; #[cfg(feature = "tracing")] -use tracing::{instrument, Span}; +use tracing::{Span, instrument}; use crate::flatbuffers::hyperlight::generated::{ - hlbool, hlboolArgs, hldouble, hldoubleArgs, hlfloat, hlfloatArgs, hlint, hlintArgs, hllong, - hllongArgs, hlsizeprefixedbuffer, hlsizeprefixedbufferArgs, hlstring, hlstringArgs, hluint, - hluintArgs, hlulong, hlulongArgs, hlvoid, hlvoidArgs, FunctionCallResult as FbFunctionCallResult, FunctionCallResultArgs as FbFunctionCallResultArgs, Parameter, ParameterType as FbParameterType, ParameterValue as FbParameterValue, - ReturnType as FbReturnType, ReturnValue as FbReturnValue, + ReturnType as FbReturnType, ReturnValue as FbReturnValue, hlbool, hlboolArgs, hldouble, + hldoubleArgs, hlfloat, hlfloatArgs, hlint, hlintArgs, hllong, hllongArgs, hlsizeprefixedbuffer, + hlsizeprefixedbufferArgs, hlstring, hlstringArgs, hluint, hluintArgs, hlulong, hlulongArgs, + hlvoid, hlvoidArgs, }; /// Supported parameter types with values for function calling. diff --git a/src/hyperlight_common/src/flatbuffer_wrappers/guest_error.rs b/src/hyperlight_common/src/flatbuffer_wrappers/guest_error.rs index 00857af21..c5a73f8a0 100644 --- a/src/hyperlight_common/src/flatbuffer_wrappers/guest_error.rs +++ b/src/hyperlight_common/src/flatbuffer_wrappers/guest_error.rs @@ -22,7 +22,7 @@ use alloc::vec::Vec; use anyhow::{Error, Result}; use flatbuffers::size_prefixed_root; #[cfg(feature = "tracing")] -use tracing::{instrument, Span}; +use tracing::{Span, instrument}; use crate::flatbuffers::hyperlight::generated::{ ErrorCode as FbErrorCode, GuestError as FbGuestError, GuestErrorArgs, diff --git a/src/hyperlight_common/src/flatbuffer_wrappers/guest_log_data.rs b/src/hyperlight_common/src/flatbuffer_wrappers/guest_log_data.rs index 36092805c..c7c63d9aa 100644 --- a/src/hyperlight_common/src/flatbuffer_wrappers/guest_log_data.rs +++ b/src/hyperlight_common/src/flatbuffer_wrappers/guest_log_data.rs @@ -17,10 +17,10 @@ limitations under the License. use alloc::string::{String, ToString}; use alloc::vec::Vec; -use anyhow::{anyhow, Error, Result}; +use anyhow::{Error, Result, anyhow}; use flatbuffers::size_prefixed_root; #[cfg(feature = "tracing")] -use tracing::{instrument, Span}; +use tracing::{Span, instrument}; use super::guest_log_level::LogLevel; use crate::flatbuffers::hyperlight::generated::{ diff --git a/src/hyperlight_common/src/flatbuffer_wrappers/guest_log_level.rs b/src/hyperlight_common/src/flatbuffer_wrappers/guest_log_level.rs index 14fa02b93..b6b44d260 100644 --- a/src/hyperlight_common/src/flatbuffer_wrappers/guest_log_level.rs +++ b/src/hyperlight_common/src/flatbuffer_wrappers/guest_log_level.rs @@ -14,11 +14,11 @@ See the License for the specific language governing permissions and limitations under the License. */ -use anyhow::{bail, Error, Result}; +use anyhow::{Error, Result, bail}; use log::Level; use strum::EnumIter; #[cfg(feature = "tracing")] -use tracing::{instrument, Span}; +use tracing::{Span, instrument}; use crate::flatbuffers::hyperlight::generated::LogLevel as FbLogLevel; diff --git a/src/hyperlight_common/src/flatbuffer_wrappers/host_function_definition.rs b/src/hyperlight_common/src/flatbuffer_wrappers/host_function_definition.rs index 23c6976da..7893105dd 100644 --- a/src/hyperlight_common/src/flatbuffer_wrappers/host_function_definition.rs +++ b/src/hyperlight_common/src/flatbuffer_wrappers/host_function_definition.rs @@ -17,10 +17,10 @@ limitations under the License. use alloc::string::{String, ToString}; use alloc::vec::Vec; -use anyhow::{anyhow, Error, Result}; +use anyhow::{Error, Result, anyhow}; use flatbuffers::{FlatBufferBuilder, WIPOffset}; #[cfg(feature = "tracing")] -use tracing::{instrument, Span}; +use tracing::{Span, instrument}; use super::function_types::{ParameterType, ReturnType}; use crate::flatbuffers::hyperlight::generated::{ diff --git a/src/hyperlight_common/src/flatbuffer_wrappers/host_function_details.rs b/src/hyperlight_common/src/flatbuffer_wrappers/host_function_details.rs index 33bd7d7c7..97d6bcec7 100644 --- a/src/hyperlight_common/src/flatbuffer_wrappers/host_function_details.rs +++ b/src/hyperlight_common/src/flatbuffer_wrappers/host_function_details.rs @@ -17,9 +17,9 @@ limitations under the License. use alloc::vec::Vec; use anyhow::{Error, Result}; -use flatbuffers::{size_prefixed_root, WIPOffset}; +use flatbuffers::{WIPOffset, size_prefixed_root}; #[cfg(feature = "tracing")] -use tracing::{instrument, Span}; +use tracing::{Span, instrument}; use super::host_function_definition::HostFunctionDefinition; use crate::flatbuffers::hyperlight::generated::{ @@ -57,11 +57,8 @@ impl HostFunctionDetails { /// Sort the host functions by name. #[cfg_attr(feature = "tracing", instrument(skip_all, parent = Span::current(), level= "Trace"))] pub fn sort_host_functions_by_name(&mut self) { - match &mut self.host_functions { - Some(host_functions) => { - host_functions.sort_by(|a, b| a.function_name.cmp(&b.function_name)) - } - None => {} + if let Some(host_functions) = &mut self.host_functions { + host_functions.sort_by(|a, b| a.function_name.cmp(&b.function_name)) } } diff --git a/src/hyperlight_common/src/flatbuffer_wrappers/util.rs b/src/hyperlight_common/src/flatbuffer_wrappers/util.rs index 184da6afe..2bf8a4b25 100644 --- a/src/hyperlight_common/src/flatbuffer_wrappers/util.rs +++ b/src/hyperlight_common/src/flatbuffer_wrappers/util.rs @@ -19,15 +19,15 @@ use alloc::vec::Vec; use flatbuffers::FlatBufferBuilder; use crate::flatbuffers::hyperlight::generated::{ - hlbool as Fbhlbool, hlboolArgs as FbhlboolArgs, hldouble as Fbhldouble, - hldoubleArgs as FbhldoubleArgs, hlfloat as Fbhlfloat, hlfloatArgs as FbhlfloatArgs, - hlint as Fbhlint, hlintArgs as FbhlintArgs, hllong as Fbhllong, hllongArgs as FbhllongArgs, - hlsizeprefixedbuffer as Fbhlsizeprefixedbuffer, + FunctionCallResult as FbFunctionCallResult, FunctionCallResultArgs as FbFunctionCallResultArgs, + ReturnValue as FbReturnValue, hlbool as Fbhlbool, hlboolArgs as FbhlboolArgs, + hldouble as Fbhldouble, hldoubleArgs as FbhldoubleArgs, hlfloat as Fbhlfloat, + hlfloatArgs as FbhlfloatArgs, hlint as Fbhlint, hlintArgs as FbhlintArgs, hllong as Fbhllong, + hllongArgs as FbhllongArgs, hlsizeprefixedbuffer as Fbhlsizeprefixedbuffer, hlsizeprefixedbufferArgs as FbhlsizeprefixedbufferArgs, hlstring as Fbhlstring, hlstringArgs as FbhlstringArgs, hluint as Fbhluint, hluintArgs as FbhluintArgs, hlulong as Fbhlulong, hlulongArgs as FbhlulongArgs, hlvoid as Fbhlvoid, - hlvoidArgs as FbhlvoidArgs, FunctionCallResult as FbFunctionCallResult, - FunctionCallResultArgs as FbFunctionCallResultArgs, ReturnValue as FbReturnValue, + hlvoidArgs as FbhlvoidArgs, }; /// Flatbuffer-encodes the given value @@ -45,7 +45,7 @@ pub trait FlatbufferSerializable { fn serialize(&self, builder: &mut FlatBufferBuilder) -> FbFunctionCallResultArgs; } -/// Implementations for basic types below +// Implementations for basic types below impl FlatbufferSerializable for () { fn serialize(&self, builder: &mut FlatBufferBuilder) -> FbFunctionCallResultArgs { diff --git a/src/hyperlight_guest/Cargo.toml b/src/hyperlight_guest/Cargo.toml index 782f7bd1b..1a5b21f31 100644 --- a/src/hyperlight_guest/Cargo.toml +++ b/src/hyperlight_guest/Cargo.toml @@ -12,6 +12,9 @@ description = """ Library to build guest applications for hyperlight. """ +[lints] +workspace = true + [features] default = ["libc", "printf"] libc = [] # compile musl libc diff --git a/src/hyperlight_guest/build.rs b/src/hyperlight_guest/build.rs index 571cf70d8..8f3a4d71c 100644 --- a/src/hyperlight_guest/build.rs +++ b/src/hyperlight_guest/build.rs @@ -105,9 +105,9 @@ fn cargo_main() { } if cfg!(windows) { - env::set_var("AR_x86_64_unknown_none", "llvm-ar"); + unsafe { env::set_var("AR_x86_64_unknown_none", "llvm-ar") }; } else { - env::set_var("AR_x86_64_pc_windows_msvc", "llvm-lib"); + unsafe { env::set_var("AR_x86_64_pc_windows_msvc", "llvm-lib") }; } cfg.compile("hyperlight_guest"); diff --git a/src/hyperlight_guest/src/chkstk.rs b/src/hyperlight_guest/src/chkstk.rs index e3e0dc4fc..706d5433e 100644 --- a/src/hyperlight_guest/src/chkstk.rs +++ b/src/hyperlight_guest/src/chkstk.rs @@ -22,7 +22,7 @@ use hyperlight_common::mem::RunMode; use crate::guest_error::{set_invalid_runmode_error, set_stack_allocate_error}; use crate::{MIN_STACK_ADDRESS, RUNNING_MODE}; -extern "win64" { +unsafe extern "win64" { fn __chkstk(); fn __chkstk_in_proc(); } diff --git a/src/hyperlight_guest/src/entrypoint.rs b/src/hyperlight_guest/src/entrypoint.rs index 2a6f6c562..c0c0c5eac 100644 --- a/src/hyperlight_guest/src/entrypoint.rs +++ b/src/hyperlight_guest/src/entrypoint.rs @@ -15,7 +15,7 @@ limitations under the License. */ use core::arch::asm; -use core::ffi::{c_char, c_void, CStr}; +use core::ffi::{CStr, c_char, c_void}; use core::ptr::copy_nonoverlapping; use hyperlight_common::mem::{HyperlightPEB, RunMode}; @@ -26,7 +26,7 @@ use crate::gdt::load_gdt; use crate::guest_error::reset_error; use crate::guest_function_call::dispatch_function; use crate::guest_logger::init_logger; -use crate::host_function_call::{outb, OutBAction}; +use crate::host_function_call::{OutBAction, outb}; use crate::idtr::load_idt; use crate::{ __security_cookie, HEAP_ALLOCATOR, MIN_STACK_ADDRESS, OS_PAGE_SIZE, OUTB_PTR, @@ -42,7 +42,7 @@ pub fn halt() { } } -#[no_mangle] +#[unsafe(no_mangle)] pub extern "C" fn abort() -> ! { abort_with_code(0) } @@ -57,17 +57,19 @@ pub fn abort_with_code(code: i32) -> ! { /// # Safety /// This function is unsafe because it dereferences a raw pointer. pub unsafe fn abort_with_code_and_message(code: i32, message_ptr: *const c_char) -> ! { - let peb_ptr = P_PEB.unwrap(); - copy_nonoverlapping( - message_ptr, - (*peb_ptr).guestPanicContextData.guestPanicContextDataBuffer as *mut c_char, - CStr::from_ptr(message_ptr).count_bytes() + 1, // +1 for null terminator - ); - outb(OutBAction::Abort as u16, code as u8); - unreachable!() + unsafe { + let peb_ptr = P_PEB.unwrap(); + copy_nonoverlapping( + message_ptr, + (*peb_ptr).guestPanicContextData.guestPanicContextDataBuffer as *mut c_char, + CStr::from_ptr(message_ptr).count_bytes() + 1, // +1 for null terminator + ); + outb(OutBAction::Abort as u16, code as u8); + unreachable!() + } } -extern "C" { +unsafe extern "C" { fn hyperlight_main(); fn srand(seed: u32); } @@ -76,7 +78,7 @@ static INIT: Once = Once::new(); // Note: entrypoint cannot currently have a stackframe >4KB, as that will invoke __chkstk on msvc // target without first having setup global `RUNNING_MODE` variable, which __chkstk relies on. -#[no_mangle] +#[unsafe(no_mangle)] pub extern "win64" fn entrypoint(peb_address: u64, seed: u64, ops: u64, max_log_level: u64) { if peb_address == 0 { panic!("PEB address is null"); @@ -88,7 +90,7 @@ pub extern "win64" fn entrypoint(peb_address: u64, seed: u64, ops: u64, max_log_ let peb_ptr = P_PEB.unwrap(); __security_cookie = peb_address ^ seed; - let srand_seed = ((peb_address << 8 ^ seed >> 4) >> 32) as u32; + let srand_seed = (((peb_address << 8) ^ (seed >> 4)) >> 32) as u32; // Set the seed for the random number generator for C code using rand; srand(srand_seed); diff --git a/src/hyperlight_guest/src/gdt.rs b/src/hyperlight_guest/src/gdt.rs index 62f70e44c..5b6e5975a 100644 --- a/src/hyperlight_guest/src/gdt.rs +++ b/src/hyperlight_guest/src/gdt.rs @@ -72,26 +72,28 @@ struct GdtPointer { } /// Load the GDT -pub unsafe fn load_gdt() { +pub(crate) unsafe fn load_gdt() { let gdt_ptr = GdtPointer { size: (core::mem::size_of::<[GdtEntry; 3]>() - 1) as u16, base: addr_of!(GDT) as *const _ as u64, }; - asm!( - "lgdt [{0}]", - "mov ax, 0x10", // Load data segment registers - "mov ds, ax", - "mov es, ax", - "mov fs, ax", - "mov gs, ax", - "mov ss, ax", - "push 0x08", // Push CS (kernel code segment) - "lea rax, [2f + rip]", // Load the next instruction's address - "push rax", // Push address onto stack - "retfq", // Far return to update CS - "2:", // Label for continued execution - in(reg) &gdt_ptr, - options(nostack, preserves_flags) - ); + unsafe { + asm!( + "lgdt [{0}]", + "mov ax, 0x10", // Load data segment registers + "mov ds, ax", + "mov es, ax", + "mov fs, ax", + "mov gs, ax", + "mov ss, ax", + "push 0x08", // Push CS (kernel code segment) + "lea rax, [2f + rip]", // Load the next instruction's address + "push rax", // Push address onto stack + "retfq", // Far return to update CS + "2:", // Label for continued execution + in(reg) &gdt_ptr, + options(nostack, preserves_flags) + ); + } } diff --git a/src/hyperlight_guest/src/guest_error.rs b/src/hyperlight_guest/src/guest_error.rs index c255789e3..c60d96f56 100644 --- a/src/hyperlight_guest/src/guest_error.rs +++ b/src/hyperlight_guest/src/guest_error.rs @@ -16,14 +16,14 @@ limitations under the License. use alloc::string::{String, ToString}; use alloc::vec::Vec; -use core::ffi::{c_char, CStr}; +use core::ffi::{CStr, c_char}; use hyperlight_common::flatbuffer_wrappers::guest_error::{ErrorCode, GuestError}; use log::error; -use crate::entrypoint::halt; -use crate::host_function_call::{outb, OutBAction}; use crate::P_PEB; +use crate::entrypoint::halt; +use crate::host_function_call::{OutBAction, outb}; pub(crate) fn write_error(error_code: ErrorCode, message: Option<&str>) { let guest_error = GuestError::new( @@ -92,12 +92,12 @@ pub(crate) fn set_error_and_halt(error_code: ErrorCode, message: &str) { halt(); } -#[no_mangle] +#[unsafe(no_mangle)] pub(crate) extern "win64" fn set_stack_allocate_error() { outb(OutBAction::Abort as u16, ErrorCode::StackOverflow as u8); } -#[no_mangle] +#[unsafe(no_mangle)] pub(crate) extern "win64" fn set_invalid_runmode_error() { panic!("Invalid run mode in __chkstk"); } @@ -107,7 +107,7 @@ pub(crate) extern "win64" fn set_invalid_runmode_error() { /// # Safety /// TODO /// cbindgen:ignore -#[no_mangle] +#[unsafe(no_mangle)] #[allow(non_camel_case_types)] pub unsafe extern "C" fn setError(code: u64, message: *const c_char) { let error_code = ErrorCode::from(code); diff --git a/src/hyperlight_guest/src/guest_function_call.rs b/src/hyperlight_guest/src/guest_function_call.rs index 60d5548db..1f4dfb96c 100644 --- a/src/hyperlight_guest/src/guest_function_call.rs +++ b/src/hyperlight_guest/src/guest_function_call.rs @@ -21,12 +21,12 @@ use hyperlight_common::flatbuffer_wrappers::function_call::{FunctionCall, Functi use hyperlight_common::flatbuffer_wrappers::function_types::ParameterType; use hyperlight_common::flatbuffer_wrappers::guest_error::ErrorCode; +use crate::REGISTERED_GUEST_FUNCTIONS; use crate::entrypoint::halt; use crate::error::{HyperlightGuestError, Result}; use crate::guest_error::{reset_error, set_error}; use crate::shared_input_data::try_pop_shared_input_data_into; use crate::shared_output_data::push_shared_output_data; -use crate::REGISTERED_GUEST_FUNCTIONS; type GuestFunc = fn(&FunctionCall) -> Result>; @@ -43,8 +43,9 @@ pub(crate) fn call_guest_function(function_call: FunctionCall) -> Result } // Find the function definition for the function call. - if let Some(registered_function_definition) = - unsafe { REGISTERED_GUEST_FUNCTIONS.get(&function_call.function_name) } + if let Some(registered_function_definition) = REGISTERED_GUEST_FUNCTIONS + .lock() + .get(&function_call.function_name) { let function_call_parameter_types: Vec = function_call .parameters @@ -68,7 +69,7 @@ pub(crate) fn call_guest_function(function_call: FunctionCall) -> Result // TODO: ideally we would define a default implementation of this with weak linkage so the guest is not required // to implement the function but its seems that weak linkage is an unstable feature so for now its probably better // to not do that. - extern "Rust" { + unsafe extern "Rust" { fn guest_dispatch_function(function_call: FunctionCall) -> Result>; } @@ -78,7 +79,7 @@ pub(crate) fn call_guest_function(function_call: FunctionCall) -> Result // This function is marked as no_mangle/inline to prevent the compiler from inlining it , if its inlined the epilogue will not be called // and we will leak memory as the epilogue will not be called as halt() is not going to return. -#[no_mangle] +#[unsafe(no_mangle)] #[inline(never)] fn internal_dispatch_function() -> Result<()> { reset_error(); diff --git a/src/hyperlight_guest/src/guest_function_register.rs b/src/hyperlight_guest/src/guest_function_register.rs index 6acdc6f43..a98ddd3c6 100644 --- a/src/hyperlight_guest/src/guest_function_register.rs +++ b/src/hyperlight_guest/src/guest_function_register.rs @@ -54,11 +54,6 @@ impl GuestFunctionRegister { } pub fn register_function(function_definition: GuestFunctionDefinition) { - unsafe { - // This is currently safe, because we are single threaded, but we - // should find a better way to do this, see issue #808 - #[allow(static_mut_refs)] - let gfd = &mut REGISTERED_GUEST_FUNCTIONS; - gfd.register(function_definition); - } + let mut gfd = REGISTERED_GUEST_FUNCTIONS.lock(); + gfd.register(function_definition); } diff --git a/src/hyperlight_guest/src/host_function_call.rs b/src/hyperlight_guest/src/host_function_call.rs index c5a496c8c..42e82d2b9 100644 --- a/src/hyperlight_guest/src/host_function_call.rs +++ b/src/hyperlight_guest/src/host_function_call.rs @@ -110,7 +110,7 @@ pub fn outb(port: u16, value: u8) { } } -extern "win64" { +unsafe extern "win64" { fn hloutb(port: u16, value: u8); } diff --git a/src/hyperlight_guest/src/host_functions.rs b/src/hyperlight_guest/src/host_functions.rs index e35fa6d2e..5dc2c39d0 100644 --- a/src/hyperlight_guest/src/host_functions.rs +++ b/src/hyperlight_guest/src/host_functions.rs @@ -24,8 +24,8 @@ use hyperlight_common::flatbuffer_wrappers::function_types::ParameterType; use hyperlight_common::flatbuffer_wrappers::guest_error::ErrorCode; use hyperlight_common::flatbuffer_wrappers::host_function_details::HostFunctionDetails; -use crate::error::{HyperlightGuestError, Result}; use crate::P_PEB; +use crate::error::{HyperlightGuestError, Result}; pub(crate) fn validate_host_function_call(function_call: &FunctionCall) -> Result<()> { // get host function details diff --git a/src/hyperlight_guest/src/idt.rs b/src/hyperlight_guest/src/idt.rs index ed3cbd757..f7016f472 100644 --- a/src/hyperlight_guest/src/idt.rs +++ b/src/hyperlight_guest/src/idt.rs @@ -15,9 +15,9 @@ limitations under the License. */ use crate::interrupt_entry::{ - _do_excp0, _do_excp1, _do_excp10, _do_excp11, _do_excp12, _do_excp13, _do_excp14, _do_excp15, - _do_excp16, _do_excp17, _do_excp18, _do_excp19, _do_excp2, _do_excp20, _do_excp3, _do_excp30, - _do_excp4, _do_excp5, _do_excp6, _do_excp7, _do_excp8, _do_excp9, + _do_excp0, _do_excp1, _do_excp2, _do_excp3, _do_excp4, _do_excp5, _do_excp6, _do_excp7, + _do_excp8, _do_excp9, _do_excp10, _do_excp11, _do_excp12, _do_excp13, _do_excp14, _do_excp15, + _do_excp16, _do_excp17, _do_excp18, _do_excp19, _do_excp20, _do_excp30, }; // An entry in the Interrupt Descriptor Table (IDT) diff --git a/src/hyperlight_guest/src/idtr.rs b/src/hyperlight_guest/src/idtr.rs index 598e62ff0..94ac8b990 100644 --- a/src/hyperlight_guest/src/idtr.rs +++ b/src/hyperlight_guest/src/idtr.rs @@ -1,6 +1,6 @@ use core::ptr::addr_of; -use crate::idt::{init_idt, IdtEntry, IDT}; +use crate::idt::{IDT, IdtEntry, init_idt}; #[repr(C, packed)] pub struct Idtr { @@ -11,13 +11,15 @@ pub struct Idtr { static mut IDTR: Idtr = Idtr { limit: 0, base: 0 }; impl Idtr { - pub unsafe fn init(&mut self, base: u64, size: u16) { + unsafe fn init(&mut self, base: u64, size: u16) { self.limit = size - 1; self.base = base; } - pub unsafe fn load(&self) { - core::arch::asm!("lidt [{}]", in(reg) self, options(readonly, nostack, preserves_flags)); + unsafe fn load(&self) { + unsafe { + core::arch::asm!("lidt [{}]", in(reg) self, options(readonly, nostack, preserves_flags)); + } } } @@ -27,6 +29,9 @@ pub(crate) unsafe fn load_idt() { let idt_size = 256 * size_of::(); let expected_base = addr_of!(IDT) as *const _ as u64; - IDTR.init(expected_base, idt_size as u16); - IDTR.load(); + #[allow(static_mut_refs)] + unsafe { + IDTR.init(expected_base, idt_size as u16); + IDTR.load(); + } } diff --git a/src/hyperlight_guest/src/interrupt_entry.rs b/src/hyperlight_guest/src/interrupt_entry.rs index 62ecd79f1..5de567ead 100644 --- a/src/hyperlight_guest/src/interrupt_entry.rs +++ b/src/hyperlight_guest/src/interrupt_entry.rs @@ -21,7 +21,7 @@ use core::arch::global_asm; use crate::interrupt_handlers::hl_exception_handler; -extern "sysv64" { +unsafe extern "sysv64" { // Exception handlers pub(crate) fn _do_excp0(); pub(crate) fn _do_excp1(); diff --git a/src/hyperlight_guest/src/interrupt_handlers.rs b/src/hyperlight_guest/src/interrupt_handlers.rs index 3b9e401ac..f3daff768 100644 --- a/src/hyperlight_guest/src/interrupt_handlers.rs +++ b/src/hyperlight_guest/src/interrupt_handlers.rs @@ -15,7 +15,7 @@ limitations under the License. */ /// Exception handler -#[no_mangle] +#[unsafe(no_mangle)] pub extern "sysv64" fn hl_exception_handler( stack_pointer: u64, exception_number: u64, diff --git a/src/hyperlight_guest/src/lib.rs b/src/hyperlight_guest/src/lib.rs index 181274c1e..57197de5a 100644 --- a/src/hyperlight_guest/src/lib.rs +++ b/src/hyperlight_guest/src/lib.rs @@ -24,8 +24,9 @@ use buddy_system_allocator::LockedHeap; use guest_function_register::GuestFunctionRegister; use hyperlight_common::flatbuffer_wrappers::guest_error::ErrorCode; use hyperlight_common::mem::{HyperlightPEB, RunMode}; +use spin::Mutex; -use crate::host_function_call::{outb, OutBAction}; +use crate::host_function_call::{OutBAction, outb}; extern crate alloc; // Modules @@ -59,10 +60,10 @@ pub mod logging; // Unresolved symbols ///cbindgen:ignore -#[no_mangle] +#[unsafe(no_mangle)] pub(crate) extern "C" fn __CxxFrameHandler3() {} ///cbindgen:ignore -#[no_mangle] +#[unsafe(no_mangle)] pub(crate) static _fltused: i32 = 0; // It looks like rust-analyzer doesn't correctly manage no_std crates, @@ -91,7 +92,7 @@ fn panic(info: &core::panic::PanicInfo) -> ! { pub(crate) static HEAP_ALLOCATOR: LockedHeap<32> = LockedHeap::<32>::empty(); ///cbindgen:ignore -#[no_mangle] +#[unsafe(no_mangle)] pub(crate) static mut __security_cookie: u64 = 0; pub(crate) static mut P_PEB: Option<*mut HyperlightPEB> = None; @@ -104,5 +105,5 @@ pub(crate) static mut OUTB_PTR_WITH_CONTEXT: Option< > = None; pub static mut RUNNING_MODE: RunMode = RunMode::None; -pub(crate) static mut REGISTERED_GUEST_FUNCTIONS: GuestFunctionRegister = - GuestFunctionRegister::new(); +pub(crate) static REGISTERED_GUEST_FUNCTIONS: Mutex = + Mutex::new(GuestFunctionRegister::new()); diff --git a/src/hyperlight_guest/src/logging.rs b/src/hyperlight_guest/src/logging.rs index 45cee65dd..95e9b868b 100644 --- a/src/hyperlight_guest/src/logging.rs +++ b/src/hyperlight_guest/src/logging.rs @@ -20,7 +20,7 @@ use alloc::vec::Vec; use hyperlight_common::flatbuffer_wrappers::guest_log_data::GuestLogData; use hyperlight_common::flatbuffer_wrappers::guest_log_level::LogLevel; -use crate::host_function_call::{outb, OutBAction}; +use crate::host_function_call::{OutBAction, outb}; use crate::shared_output_data::push_shared_output_data; fn write_log_data( diff --git a/src/hyperlight_guest/src/memory.rs b/src/hyperlight_guest/src/memory.rs index 70390cbdc..247ca45cd 100644 --- a/src/hyperlight_guest/src/memory.rs +++ b/src/hyperlight_guest/src/memory.rs @@ -81,9 +81,9 @@ unsafe fn alloc_helper(size: usize, zero: bool) -> *mut c_void { /// /// # Safety /// The returned pointer must be freed with `memory::free` when it is no longer needed, otherwise memory will leak. -#[no_mangle] +#[unsafe(no_mangle)] pub unsafe extern "C" fn malloc(size: usize) -> *mut c_void { - alloc_helper(size, false) + unsafe { alloc_helper(size, false) } } /// Allocates a block of memory for an array of `nmemb` elements, each of `size` bytes. @@ -91,20 +91,22 @@ pub unsafe extern "C" fn malloc(size: usize) -> *mut c_void { /// /// # Safety /// The returned pointer must be freed with `memory::free` when it is no longer needed, otherwise memory will leak. -#[no_mangle] +#[unsafe(no_mangle)] pub unsafe extern "C" fn calloc(nmemb: usize, size: usize) -> *mut c_void { - let total_size = nmemb - .checked_mul(size) - .expect("nmemb * size should not overflow in calloc"); + unsafe { + let total_size = nmemb + .checked_mul(size) + .expect("nmemb * size should not overflow in calloc"); - alloc_helper(total_size, true) + alloc_helper(total_size, true) + } } /// Frees the memory block pointed to by `ptr`. /// /// # Safety /// `ptr` must be a pointer to a memory block previously allocated by `memory::malloc`, `memory::calloc`, or `memory::realloc`. -#[no_mangle] +#[unsafe(no_mangle)] pub unsafe extern "C" fn free(ptr: *mut c_void) { if !ptr.is_null() { unsafe { @@ -120,24 +122,23 @@ pub unsafe extern "C" fn free(ptr: *mut c_void) { /// /// # Safety /// `ptr` must be a pointer to a memory block previously allocated by `memory::malloc`, `memory::calloc`, or `memory::realloc`. -#[no_mangle] +#[unsafe(no_mangle)] pub unsafe extern "C" fn realloc(ptr: *mut c_void, size: usize) -> *mut c_void { if ptr.is_null() { // If the pointer is null, treat as a malloc - return malloc(size); + return unsafe { malloc(size) }; } if size == 0 { // If the size is 0, treat as a free and return null - free(ptr); + unsafe { free(ptr) }; return ptr::null_mut(); } + let total_new_size = size + .checked_add(size_of::()) + .expect("data and layout size should not overflow in realloc"); unsafe { - let total_new_size = size - .checked_add(size_of::()) - .expect("data and layout size should not overflow in realloc"); - let block_start = (ptr as *const Layout).sub(1); let old_layout = block_start.read(); let new_layout = Layout::from_size_align(total_new_size, MAX_ALIGN).unwrap(); diff --git a/src/hyperlight_guest/src/print.rs b/src/hyperlight_guest/src/print.rs index b7dd8404f..60a963f30 100644 --- a/src/hyperlight_guest/src/print.rs +++ b/src/hyperlight_guest/src/print.rs @@ -16,53 +16,50 @@ limitations under the License. use alloc::string::String; use alloc::vec::Vec; -use core::ffi::{c_char, CStr}; +use core::ffi::{CStr, c_char}; use core::mem; use hyperlight_common::flatbuffer_wrappers::function_types::{ParameterValue, ReturnType}; +use spin::Mutex; use crate::host_function_call::call_host_function; const BUFFER_SIZE: usize = 1000; -static mut MESSAGE_BUFFER: Vec = Vec::new(); +static MESSAGE_BUFFER: Mutex> = Mutex::new(Vec::new()); /// Exposes a C API to allow the guest to print a string -/// -/// # Safety -/// This function is not thread safe -#[no_mangle] -#[allow(static_mut_refs)] -pub unsafe extern "C" fn _putchar(c: c_char) { +#[unsafe(no_mangle)] +pub extern "C" fn _putchar(c: c_char) { let char = c as u8; + let mut locked_buffer = MESSAGE_BUFFER.lock(); // Extend buffer capacity if it's empty (like `with_capacity` in lazy_static). // TODO: replace above Vec::new() with Vec::with_capacity once it's stable in const contexts. - if MESSAGE_BUFFER.capacity() == 0 { - MESSAGE_BUFFER.reserve(BUFFER_SIZE); + if locked_buffer.capacity() == 0 { + locked_buffer.reserve(BUFFER_SIZE); } - MESSAGE_BUFFER.push(char); + locked_buffer.push(char); - if MESSAGE_BUFFER.len() == BUFFER_SIZE || char == b'\0' { + if locked_buffer.len() == BUFFER_SIZE || char == b'\0' { let str = if char == b'\0' { - CStr::from_bytes_until_nul(&MESSAGE_BUFFER) - .expect("No null byte in buffer") + CStr::from_bytes_until_nul(&locked_buffer) + .expect("No null byte in buffer") // This expect is safe since we know there is a null byte .to_string_lossy() .into_owned() } else { - String::from_utf8(mem::take(&mut MESSAGE_BUFFER)) + String::from_utf8(mem::take(&mut locked_buffer)) .expect("Failed to convert buffer to string") }; + locked_buffer.clear(); + call_host_function( "HostPrint", Some(Vec::from(&[ParameterValue::String(str)])), ReturnType::Void, ) .expect("Failed to call HostPrint"); - - // Clear the buffer after sending - MESSAGE_BUFFER.clear(); } } diff --git a/src/hyperlight_guest/src/security_check.rs b/src/hyperlight_guest/src/security_check.rs index b21a94af8..3aa0a59a2 100644 --- a/src/hyperlight_guest/src/security_check.rs +++ b/src/hyperlight_guest/src/security_check.rs @@ -23,7 +23,7 @@ use crate::__security_cookie; use crate::guest_error::set_error_and_halt; ///cbindgen:ignore -#[no_mangle] +#[unsafe(no_mangle)] pub(crate) extern "C" fn __security_check_cookie(cookie: u64) { unsafe { if __security_cookie != cookie { diff --git a/src/hyperlight_guest/src/setjmp.rs b/src/hyperlight_guest/src/setjmp.rs index 2d9139205..34a658c00 100644 --- a/src/hyperlight_guest/src/setjmp.rs +++ b/src/hyperlight_guest/src/setjmp.rs @@ -96,15 +96,15 @@ ok: /* Adapt the calling convention of the above to the native "C" calling * convention. */ -extern "win64" { +unsafe extern "win64" { fn win64_setjmp(x: u64) -> u64; fn win64_longjmp(x: u64, y: u64) -> !; } -#[no_mangle] +#[unsafe(no_mangle)] extern "C" fn setjmp(x: u64) -> u64 { unsafe { win64_setjmp(x) } } -#[no_mangle] +#[unsafe(no_mangle)] extern "C" fn longjmp(x: u64, y: u64) -> ! { unsafe { win64_longjmp(x, y) } } diff --git a/src/hyperlight_guest/src/shared_input_data.rs b/src/hyperlight_guest/src/shared_input_data.rs index 8d943db07..ce3df4af3 100644 --- a/src/hyperlight_guest/src/shared_input_data.rs +++ b/src/hyperlight_guest/src/shared_input_data.rs @@ -21,8 +21,8 @@ use core::slice::from_raw_parts_mut; use hyperlight_common::flatbuffer_wrappers::guest_error::ErrorCode; -use crate::error::{HyperlightGuestError, Result}; use crate::P_PEB; +use crate::error::{HyperlightGuestError, Result}; // Pops the top element from the shared input data buffer and returns it as a T pub fn try_pop_shared_input_data_into() -> Result diff --git a/src/hyperlight_guest/src/shared_output_data.rs b/src/hyperlight_guest/src/shared_output_data.rs index 520a369f3..a7259ccae 100644 --- a/src/hyperlight_guest/src/shared_output_data.rs +++ b/src/hyperlight_guest/src/shared_output_data.rs @@ -21,8 +21,8 @@ use core::slice::from_raw_parts_mut; use hyperlight_common::flatbuffer_wrappers::guest_error::ErrorCode; -use crate::error::{HyperlightGuestError, Result}; use crate::P_PEB; +use crate::error::{HyperlightGuestError, Result}; pub fn push_shared_output_data(data: Vec) -> Result<()> { let peb_ptr = unsafe { P_PEB.unwrap() }; diff --git a/src/hyperlight_guest_capi/Cargo.toml b/src/hyperlight_guest_capi/Cargo.toml index 843f2577e..cab61a50e 100644 --- a/src/hyperlight_guest_capi/Cargo.toml +++ b/src/hyperlight_guest_capi/Cargo.toml @@ -15,6 +15,7 @@ workspace = true hyperlight-guest = { workspace = true, default-features = true } hyperlight-common = { workspace = true, default-features = false } log = { version = "0.4", default-features = false } +spin = "0.9.8" [build-dependencies] cbindgen = "0.28.0" diff --git a/src/hyperlight_guest_capi/src/dispatch.rs b/src/hyperlight_guest_capi/src/dispatch.rs index eacd7b374..1695d85d0 100644 --- a/src/hyperlight_guest_capi/src/dispatch.rs +++ b/src/hyperlight_guest_capi/src/dispatch.rs @@ -1,7 +1,7 @@ use alloc::boxed::Box; use alloc::slice; use alloc::vec::Vec; -use core::ffi::{c_char, CStr}; +use core::ffi::{CStr, c_char}; use core::mem; use hyperlight_common::flatbuffer_wrappers::function_call::FunctionCall; @@ -11,22 +11,25 @@ use hyperlight_guest::error::{HyperlightGuestError, Result}; use hyperlight_guest::guest_function_definition::GuestFunctionDefinition; use hyperlight_guest::guest_function_register::GuestFunctionRegister; use hyperlight_guest::host_function_call::call_host_function; +use spin::Mutex; use crate::types::{FfiFunctionCall, FfiVec}; -static mut REGISTERED_C_GUEST_FUNCTIONS: GuestFunctionRegister = GuestFunctionRegister::new(); +static REGISTERED_C_GUEST_FUNCTIONS: Mutex = + Mutex::new(GuestFunctionRegister::new()); type CGuestFunc = extern "C" fn(&FfiFunctionCall) -> Box; -extern "C" { +unsafe extern "C" { // NOTE *mut FfiVec must be a Box. This will be the case as long as the guest // returns a FfiVec that they created using the c-api hl_flatbuffer_result_from_* functions. fn c_guest_dispatch_function(function_call: &FfiFunctionCall) -> *mut FfiVec; } -#[no_mangle] +#[unsafe(no_mangle)] pub fn guest_dispatch_function(function_call: FunctionCall) -> Result> { - if let Some(registered_func) = - unsafe { REGISTERED_C_GUEST_FUNCTIONS.get(&function_call.function_name) } + if let Some(registered_func) = REGISTERED_C_GUEST_FUNCTIONS + .lock() + .get(&function_call.function_name) { let function_call_parameter_types: Vec = function_call .parameters @@ -64,8 +67,11 @@ pub fn guest_dispatch_function(function_call: FunctionCall) -> Result> { } } -#[no_mangle] -pub extern "C" fn hl_register_function_definition( +/// # Safety +/// +/// Dereferences the given raw pointers +#[unsafe(no_mangle)] +pub unsafe extern "C" fn hl_register_function_definition( function_name: *const c_char, func_ptr: CGuestFunc, param_no: usize, @@ -79,12 +85,11 @@ pub extern "C" fn hl_register_function_definition( let func_def = GuestFunctionDefinition::new(func_name, func_params, return_type, func_ptr as usize); - #[allow(static_mut_refs)] - unsafe { &mut REGISTERED_C_GUEST_FUNCTIONS }.register(func_def); + REGISTERED_C_GUEST_FUNCTIONS.lock().register(func_def); } /// The caller is responsible for freeing the memory associated with given `FfiFunctionCall`. -#[no_mangle] +#[unsafe(no_mangle)] pub extern "C" fn hl_call_host_function(function_call: &FfiFunctionCall) { let parameters = unsafe { function_call.copy_parameters() }; let func_name = unsafe { function_call.copy_function_name() }; diff --git a/src/hyperlight_guest_capi/src/error.rs b/src/hyperlight_guest_capi/src/error.rs index 948abae3a..859e41a55 100644 --- a/src/hyperlight_guest_capi/src/error.rs +++ b/src/hyperlight_guest_capi/src/error.rs @@ -3,19 +3,25 @@ use core::ffi::c_char; use hyperlight_common::flatbuffer_wrappers::guest_error::ErrorCode; use hyperlight_guest::guest_error::setError; -#[no_mangle] -pub extern "C" fn hl_set_error(err: ErrorCode, message: *const c_char) { +/// # Safety +/// +/// Dereferences the given raw pointer. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn hl_set_error(err: ErrorCode, message: *const c_char) { unsafe { setError(err.into(), message); } } -#[no_mangle] +#[unsafe(no_mangle)] pub extern "C" fn hl_abort_with_code(err: i32) { hyperlight_guest::entrypoint::abort_with_code(err); } -#[no_mangle] -pub extern "C" fn hl_abort_with_code_and_message(err: i32, message: *const c_char) { +/// # Safety +/// +/// Dereferences the given raw pointer. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn hl_abort_with_code_and_message(err: i32, message: *const c_char) { unsafe { hyperlight_guest::entrypoint::abort_with_code_and_message(err, message) }; } diff --git a/src/hyperlight_guest_capi/src/flatbuffer.rs b/src/hyperlight_guest_capi/src/flatbuffer.rs index 33cfdbb4b..ae6b0b8c8 100644 --- a/src/hyperlight_guest_capi/src/flatbuffer.rs +++ b/src/hyperlight_guest_capi/src/flatbuffer.rs @@ -1,5 +1,5 @@ use alloc::boxed::Box; -use core::ffi::{c_char, CStr}; +use core::ffi::{CStr, c_char}; use hyperlight_common::flatbuffer_wrappers::util::get_flatbuffer_result; use hyperlight_guest::host_function_call::get_host_return_value; @@ -10,65 +10,74 @@ use crate::types::FfiVec; // is to match the names of the variants in hl_ReturnType, // which is used in the C macros in macro.h -#[no_mangle] +#[unsafe(no_mangle)] pub extern "C" fn hl_flatbuffer_result_from_Int(value: i32) -> Box { let vec = get_flatbuffer_result(value); Box::new(unsafe { FfiVec::from_vec(vec) }) } -#[no_mangle] +#[unsafe(no_mangle)] pub extern "C" fn hl_flatbuffer_result_from_UInt(value: u32) -> Box { let vec = get_flatbuffer_result(value); Box::new(unsafe { FfiVec::from_vec(vec) }) } -#[no_mangle] +#[unsafe(no_mangle)] pub extern "C" fn hl_flatbuffer_result_from_Long(value: i64) -> Box { let vec = get_flatbuffer_result(value); Box::new(unsafe { FfiVec::from_vec(vec) }) } -#[no_mangle] +#[unsafe(no_mangle)] pub extern "C" fn hl_flatbuffer_result_from_ULong(value: u64) -> Box { let vec = get_flatbuffer_result(value); Box::new(unsafe { FfiVec::from_vec(vec) }) } -#[no_mangle] +#[unsafe(no_mangle)] pub extern "C" fn hl_flatbuffer_result_from_Float(value: f32) -> Box { let vec = get_flatbuffer_result(value); Box::new(unsafe { FfiVec::from_vec(vec) }) } -#[no_mangle] +#[unsafe(no_mangle)] pub extern "C" fn hl_flatbuffer_result_from_Double(value: f64) -> Box { let vec = get_flatbuffer_result(value); Box::new(unsafe { FfiVec::from_vec(vec) }) } -#[no_mangle] +#[unsafe(no_mangle)] pub extern "C" fn hl_flatbuffer_result_from_Void() -> Box { let vec = get_flatbuffer_result(()); Box::new(unsafe { FfiVec::from_vec(vec) }) } -#[no_mangle] -pub extern "C" fn hl_flatbuffer_result_from_String(value: *const c_char) -> Box { +/// # Safety +/// +/// Dereferences the given raw pointer. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn hl_flatbuffer_result_from_String(value: *const c_char) -> Box { let str = unsafe { CStr::from_ptr(value) }; let vec = get_flatbuffer_result(str.to_string_lossy().as_ref()); Box::new(unsafe { FfiVec::from_vec(vec) }) } -#[no_mangle] -pub extern "C" fn hl_flatbuffer_result_from_Bytes(data: *const u8, len: usize) -> Box { +/// # Safety +/// +/// Dereferences the given raw pointer. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn hl_flatbuffer_result_from_Bytes( + data: *const u8, + len: usize, +) -> Box { let slice = unsafe { core::slice::from_raw_parts(data, len) }; let vec = get_flatbuffer_result(slice); @@ -78,23 +87,23 @@ pub extern "C" fn hl_flatbuffer_result_from_Bytes(data: *const u8, len: usize) - //--- Functions for getting values returned by host functions calls -#[no_mangle] +#[unsafe(no_mangle)] pub extern "C" fn hl_get_host_return_value_as_Int() -> i32 { get_host_return_value().expect("Unable to get host return value as int") } -#[no_mangle] +#[unsafe(no_mangle)] pub extern "C" fn hl_get_host_return_value_as_UInt() -> u32 { get_host_return_value().expect("Unable to get host return value as uint") } // the same for long, ulong -#[no_mangle] +#[unsafe(no_mangle)] pub extern "C" fn hl_get_host_return_value_as_Long() -> i64 { get_host_return_value().expect("Unable to get host return value as long") } -#[no_mangle] +#[unsafe(no_mangle)] pub extern "C" fn hl_get_host_return_value_as_ULong() -> u64 { get_host_return_value().expect("Unable to get host return value as ulong") } diff --git a/src/hyperlight_guest_capi/src/logging.rs b/src/hyperlight_guest_capi/src/logging.rs index 8bba45e32..b906669dc 100644 --- a/src/hyperlight_guest_capi/src/logging.rs +++ b/src/hyperlight_guest_capi/src/logging.rs @@ -1,7 +1,10 @@ use core::ffi::c_char; -#[no_mangle] -pub extern "C" fn hl_log( +/// # Safety +/// +/// Dereferences the given raw pointers. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn hl_log( level: log::Level, message: *const c_char, line: i32, diff --git a/src/hyperlight_guest_capi/src/types/function_call.rs b/src/hyperlight_guest_capi/src/types/function_call.rs index 391ebef82..7147d13d5 100644 --- a/src/hyperlight_guest_capi/src/types/function_call.rs +++ b/src/hyperlight_guest_capi/src/types/function_call.rs @@ -3,7 +3,7 @@ use alloc::ffi::CString; use alloc::slice; use alloc::string::String; use alloc::vec::Vec; -use core::ffi::{c_char, CStr}; +use core::ffi::{CStr, c_char}; use hyperlight_common::flatbuffer_wrappers::function_call::FunctionCall; use hyperlight_common::flatbuffer_wrappers::function_types::{ParameterValue, ReturnType}; diff --git a/src/hyperlight_guest_capi/src/types/parameter.rs b/src/hyperlight_guest_capi/src/types/parameter.rs index 8a7d18a30..08515c752 100644 --- a/src/hyperlight_guest_capi/src/types/parameter.rs +++ b/src/hyperlight_guest_capi/src/types/parameter.rs @@ -1,5 +1,5 @@ use alloc::ffi::CString; -use core::ffi::{c_char, CStr}; +use core::ffi::{CStr, c_char}; use hyperlight_common::flatbuffer_wrappers::function_types::{ParameterType, ParameterValue}; use hyperlight_guest::error::Result; diff --git a/src/hyperlight_host/benches/benchmarks.rs b/src/hyperlight_host/benches/benchmarks.rs index db71d8a95..84372d6ee 100644 --- a/src/hyperlight_host/benches/benchmarks.rs +++ b/src/hyperlight_host/benches/benchmarks.rs @@ -16,13 +16,13 @@ limitations under the License. use std::sync::{Arc, Mutex}; -use criterion::{criterion_group, criterion_main, Criterion}; +use criterion::{Criterion, criterion_group, criterion_main}; use hyperlight_common::flatbuffer_wrappers::function_types::{ParameterValue, ReturnType}; +use hyperlight_host::GuestBinary; use hyperlight_host::func::HostFunction2; use hyperlight_host::sandbox::{MultiUseSandbox, UninitializedSandbox}; use hyperlight_host::sandbox_state::sandbox::EvolvableSandbox; use hyperlight_host::sandbox_state::transition::Noop; -use hyperlight_host::GuestBinary; use hyperlight_testing::simple_guest_as_string; fn create_uninit_sandbox() -> UninitializedSandbox { diff --git a/src/hyperlight_host/examples/func_ctx/main.rs b/src/hyperlight_host/examples/func_ctx/main.rs index 2967616e4..4738de77e 100644 --- a/src/hyperlight_host/examples/func_ctx/main.rs +++ b/src/hyperlight_host/examples/func_ctx/main.rs @@ -19,7 +19,7 @@ use hyperlight_host::func::call_ctx::MultiUseGuestCallContext; use hyperlight_host::sandbox::{MultiUseSandbox, UninitializedSandbox}; use hyperlight_host::sandbox_state::sandbox::EvolvableSandbox; use hyperlight_host::sandbox_state::transition::Noop; -use hyperlight_host::{new_error, GuestBinary, Result}; +use hyperlight_host::{GuestBinary, Result, new_error}; use hyperlight_testing::simple_guest_as_string; fn main() { diff --git a/src/hyperlight_host/examples/guest-debugging/main.rs b/src/hyperlight_host/examples/guest-debugging/main.rs index da3010b9c..925312201 100644 --- a/src/hyperlight_host/examples/guest-debugging/main.rs +++ b/src/hyperlight_host/examples/guest-debugging/main.rs @@ -19,9 +19,9 @@ use std::thread; use hyperlight_common::flatbuffer_wrappers::function_types::{ParameterValue, ReturnType}; use hyperlight_host::func::HostFunction0; +use hyperlight_host::sandbox::SandboxConfiguration; #[cfg(gdb)] use hyperlight_host::sandbox::config::DebugInfo; -use hyperlight_host::sandbox::SandboxConfiguration; use hyperlight_host::sandbox_state::sandbox::EvolvableSandbox; use hyperlight_host::sandbox_state::transition::Noop; use hyperlight_host::{MultiUseSandbox, UninitializedSandbox}; @@ -89,7 +89,7 @@ mod tests { use std::process::{Command, Stdio}; use std::time::Duration; - use hyperlight_host::{new_error, Result}; + use hyperlight_host::{Result, new_error}; use io::{BufReader, BufWriter, Read, Write}; use super::*; diff --git a/src/hyperlight_host/examples/metrics/main.rs b/src/hyperlight_host/examples/metrics/main.rs index 2028c21f7..d97dfe2ec 100644 --- a/src/hyperlight_host/examples/metrics/main.rs +++ b/src/hyperlight_host/examples/metrics/main.rs @@ -16,13 +16,13 @@ limitations under the License. extern crate hyperlight_host; use std::sync::{Arc, Mutex}; -use std::thread::{spawn, JoinHandle}; +use std::thread::{JoinHandle, spawn}; use hyperlight_common::flatbuffer_wrappers::function_types::{ParameterValue, ReturnType}; use hyperlight_host::sandbox::uninitialized::UninitializedSandbox; use hyperlight_host::sandbox_state::sandbox::EvolvableSandbox; use hyperlight_host::sandbox_state::transition::Noop; -use hyperlight_host::{set_metrics_registry, GuestBinary, MultiUseSandbox, Result}; +use hyperlight_host::{GuestBinary, MultiUseSandbox, Result, set_metrics_registry}; use hyperlight_testing::simple_guest_as_string; use lazy_static::lazy_static; use prometheus::Registry; diff --git a/src/hyperlight_host/examples/otlp_tracing/main.rs b/src/hyperlight_host/examples/otlp_tracing/main.rs index ccddc3626..4864ac99d 100644 --- a/src/hyperlight_host/examples/otlp_tracing/main.rs +++ b/src/hyperlight_host/examples/otlp_tracing/main.rs @@ -18,7 +18,7 @@ use hyperlight_common::flatbuffer_wrappers::function_types::{ParameterValue, Ret //use opentelemetry_sdk::resource::ResourceBuilder; use opentelemetry_sdk::trace::SdkTracerProvider; use rand::Rng; -use tracing::{span, Level}; +use tracing::{Level, span}; use tracing_opentelemetry::OpenTelemetryLayer; use tracing_subscriber::layer::SubscriberExt; use tracing_subscriber::util::SubscriberInitExt; @@ -26,7 +26,7 @@ extern crate hyperlight_host; use std::error::Error; use std::io::stdin; use std::sync::{Arc, Mutex}; -use std::thread::{self, spawn, JoinHandle}; +use std::thread::{self, JoinHandle, spawn}; use hyperlight_host::sandbox::uninitialized::UninitializedSandbox; use hyperlight_host::sandbox_state::sandbox::EvolvableSandbox; @@ -34,7 +34,7 @@ use hyperlight_host::sandbox_state::transition::Noop; use hyperlight_host::{GuestBinary, MultiUseSandbox, Result as HyperlightResult}; use hyperlight_testing::simple_guest_as_string; use opentelemetry::trace::TracerProvider; -use opentelemetry::{global, KeyValue}; +use opentelemetry::{KeyValue, global}; use opentelemetry_otlp::{SpanExporter, WithExportConfig}; //use opentelemetry_sdk::runtime::Tokio; use opentelemetry_sdk::Resource; diff --git a/src/hyperlight_host/examples/tracing/main.rs b/src/hyperlight_host/examples/tracing/main.rs index 1778a3d47..f8dbb5dcd 100644 --- a/src/hyperlight_host/examples/tracing/main.rs +++ b/src/hyperlight_host/examples/tracing/main.rs @@ -15,10 +15,10 @@ limitations under the License. */ use hyperlight_common::flatbuffer_wrappers::function_types::{ParameterValue, ReturnType}; -use tracing::{span, Level}; +use tracing::{Level, span}; extern crate hyperlight_host; use std::sync::{Arc, Mutex}; -use std::thread::{spawn, JoinHandle}; +use std::thread::{JoinHandle, spawn}; use hyperlight_host::sandbox::uninitialized::UninitializedSandbox; use hyperlight_host::sandbox_state::sandbox::EvolvableSandbox; diff --git a/src/hyperlight_host/src/func/call_ctx.rs b/src/hyperlight_host/src/func/call_ctx.rs index bc48e249c..da0907ce0 100644 --- a/src/hyperlight_host/src/func/call_ctx.rs +++ b/src/hyperlight_host/src/func/call_ctx.rs @@ -17,7 +17,7 @@ limitations under the License. use hyperlight_common::flatbuffer_wrappers::function_types::{ ParameterValue, ReturnType, ReturnValue, }; -use tracing::{instrument, Span}; +use tracing::{Span, instrument}; use super::guest_dispatch::call_function_on_guest; use crate::{MultiUseSandbox, Result}; diff --git a/src/hyperlight_host/src/func/guest_dispatch.rs b/src/hyperlight_host/src/func/guest_dispatch.rs index 4462a8a66..bedd5481d 100644 --- a/src/hyperlight_host/src/func/guest_dispatch.rs +++ b/src/hyperlight_host/src/func/guest_dispatch.rs @@ -18,12 +18,12 @@ use hyperlight_common::flatbuffer_wrappers::function_call::{FunctionCall, Functi use hyperlight_common::flatbuffer_wrappers::function_types::{ ParameterValue, ReturnType, ReturnValue, }; -use tracing::{instrument, Span}; +use tracing::{Span, instrument}; use super::guest_err::check_for_guest_error; +use crate::HyperlightError::GuestExecutionHungOnHostFunctionCall; use crate::hypervisor::hypervisor_handler::HypervisorHandlerAction; use crate::sandbox::WrapperGetter; -use crate::HyperlightError::GuestExecutionHungOnHostFunctionCall; use crate::{HyperlightError, Result}; /// Call a guest function by name, using the given `wrapper_getter`. @@ -117,7 +117,7 @@ mod tests { use crate::sandbox::uninitialized::GuestBinary; use crate::sandbox_state::sandbox::EvolvableSandbox; use crate::sandbox_state::transition::Noop; - use crate::{new_error, HyperlightError, MultiUseSandbox, Result, UninitializedSandbox}; + use crate::{HyperlightError, MultiUseSandbox, Result, UninitializedSandbox, new_error}; // simple function fn test_function0(_: MultiUseGuestCallContext) -> Result { diff --git a/src/hyperlight_host/src/func/guest_err.rs b/src/hyperlight_host/src/func/guest_err.rs index 58baa8c56..082a445ae 100644 --- a/src/hyperlight_host/src/func/guest_err.rs +++ b/src/hyperlight_host/src/func/guest_err.rs @@ -22,7 +22,7 @@ use crate::error::HyperlightError::{GuestError, OutBHandlingError, StackOverflow use crate::mem::shared_mem::HostSharedMemory; use crate::sandbox::mem_mgr::MemMgrWrapper; use crate::sandbox::metrics::SandboxMetric::GuestErrorCount; -use crate::{int_counter_vec_inc, log_then_return, Result}; +use crate::{Result, int_counter_vec_inc, log_then_return}; /// Check for a guest error and return an `Err` if one was found, /// and `Ok` if one was not found. pub(crate) fn check_for_guest_error(mgr: &MemMgrWrapper) -> Result<()> { diff --git a/src/hyperlight_host/src/func/host_functions.rs b/src/hyperlight_host/src/func/host_functions.rs index ce30d9c45..35108a537 100644 --- a/src/hyperlight_host/src/func/host_functions.rs +++ b/src/hyperlight_host/src/func/host_functions.rs @@ -20,12 +20,12 @@ use std::sync::{Arc, Mutex}; use hyperlight_common::flatbuffer_wrappers::function_types::ParameterValue; use hyperlight_common::flatbuffer_wrappers::host_function_definition::HostFunctionDefinition; use paste::paste; -use tracing::{instrument, Span}; +use tracing::{Span, instrument}; use super::{HyperlightFunction, SupportedParameterType, SupportedReturnType}; -use crate::sandbox::{ExtraAllowedSyscall, UninitializedSandbox}; use crate::HyperlightError::UnexpectedNoOfArguments; -use crate::{log_then_return, new_error, Result}; +use crate::sandbox::{ExtraAllowedSyscall, UninitializedSandbox}; +use crate::{Result, log_then_return, new_error}; macro_rules! host_function { // Special case for zero parameters diff --git a/src/hyperlight_host/src/func/mod.rs b/src/hyperlight_host/src/func/mod.rs index 6d6c56c21..94e420330 100644 --- a/src/hyperlight_host/src/func/mod.rs +++ b/src/hyperlight_host/src/func/mod.rs @@ -14,7 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ -use crate::{new_error, Result}; +use crate::{Result, new_error}; /// Context structures used to allow the user to call one or more guest /// functions on the same Hyperlight sandbox instance, all from within the /// same state and mutual exclusion context. @@ -50,7 +50,7 @@ pub use hyperlight_common::flatbuffer_wrappers::function_types::ReturnType; pub use hyperlight_common::flatbuffer_wrappers::function_types::ReturnValue; pub use param_type::SupportedParameterType; pub use ret_type::SupportedReturnType; -use tracing::{instrument, Span}; +use tracing::{Span, instrument}; type HLFunc = Arc) -> Result + Send>>>; @@ -81,8 +81,6 @@ impl HyperlightFunction { pub use host_functions::HostFunction0; /// Re-export for `HostFunction1` trait pub use host_functions::HostFunction1; -/// Re-export for `HostFunction10` trait -pub use host_functions::HostFunction10; /// Re-export for `HostFunction2` trait pub use host_functions::HostFunction2; /// Re-export for `HostFunction3` trait @@ -99,3 +97,5 @@ pub use host_functions::HostFunction7; pub use host_functions::HostFunction8; /// Re-export for `HostFunction9` trait pub use host_functions::HostFunction9; +/// Re-export for `HostFunction10` trait +pub use host_functions::HostFunction10; diff --git a/src/hyperlight_host/src/func/param_type.rs b/src/hyperlight_host/src/func/param_type.rs index e64010ed1..a6650c831 100644 --- a/src/hyperlight_host/src/func/param_type.rs +++ b/src/hyperlight_host/src/func/param_type.rs @@ -15,10 +15,10 @@ limitations under the License. */ use hyperlight_common::flatbuffer_wrappers::function_types::{ParameterType, ParameterValue}; -use tracing::{instrument, Span}; +use tracing::{Span, instrument}; use crate::HyperlightError::ParameterValueConversionFailure; -use crate::{log_then_return, Result}; +use crate::{Result, log_then_return}; /// This is a marker trait that is used to indicate that a type is a /// valid Hyperlight parameter type. diff --git a/src/hyperlight_host/src/func/ret_type.rs b/src/hyperlight_host/src/func/ret_type.rs index 0436d5816..6686b649c 100644 --- a/src/hyperlight_host/src/func/ret_type.rs +++ b/src/hyperlight_host/src/func/ret_type.rs @@ -15,10 +15,10 @@ limitations under the License. */ use hyperlight_common::flatbuffer_wrappers::function_types::{ReturnType, ReturnValue}; -use tracing::{instrument, Span}; +use tracing::{Span, instrument}; use crate::HyperlightError::ReturnValueConversionFailure; -use crate::{log_then_return, Result}; +use crate::{Result, log_then_return}; /// This is a marker trait that is used to indicate that a type is a valid Hyperlight return type. pub trait SupportedReturnType { diff --git a/src/hyperlight_host/src/hyperlight_surrogate/Cargo.toml_temp_name b/src/hyperlight_host/src/hyperlight_surrogate/Cargo.toml_temp_name index 935fde038..143f3a45a 100644 --- a/src/hyperlight_host/src/hyperlight_surrogate/Cargo.toml_temp_name +++ b/src/hyperlight_host/src/hyperlight_surrogate/Cargo.toml_temp_name @@ -1,7 +1,7 @@ [package] name = "hyperlight_surrogate" version = "0.1.0" -edition = "2021" +edition = "2024" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html diff --git a/src/hyperlight_host/src/hypervisor/crashdump.rs b/src/hyperlight_host/src/hypervisor/crashdump.rs index a70dc34c1..5a79be356 100644 --- a/src/hyperlight_host/src/hypervisor/crashdump.rs +++ b/src/hyperlight_host/src/hypervisor/crashdump.rs @@ -3,7 +3,7 @@ use std::io::Write; use tempfile::NamedTempFile; use super::Hypervisor; -use crate::{new_error, Result}; +use crate::{Result, new_error}; /// Dump registers + memory regions + raw memory to a tempfile #[cfg(crashdump)] diff --git a/src/hyperlight_host/src/hypervisor/gdb/event_loop.rs b/src/hyperlight_host/src/hypervisor/gdb/event_loop.rs index ee009caa1..bf799126e 100644 --- a/src/hyperlight_host/src/hypervisor/gdb/event_loop.rs +++ b/src/hyperlight_host/src/hypervisor/gdb/event_loop.rs @@ -18,7 +18,7 @@ use gdbstub::common::Signal; use gdbstub::conn::ConnectionExt; use gdbstub::stub::run_blocking::{self, WaitForStopReasonError}; use gdbstub::stub::{BaseStopReason, DisconnectReason, GdbStub, SingleThreadStopReason}; -use libc::{pthread_kill, SIGRTMIN}; +use libc::{SIGRTMIN, pthread_kill}; use super::x86_64_target::HyperlightSandboxTarget; use super::{DebugResponse, GdbTargetError, VcpuStopReason}; diff --git a/src/hyperlight_host/src/hypervisor/gdb/x86_64_target.rs b/src/hyperlight_host/src/hypervisor/gdb/x86_64_target.rs index 51bca3d19..0930d26ae 100644 --- a/src/hyperlight_host/src/hypervisor/gdb/x86_64_target.rs +++ b/src/hyperlight_host/src/hypervisor/gdb/x86_64_target.rs @@ -17,11 +17,11 @@ limitations under the License. use crossbeam_channel::TryRecvError; use gdbstub::arch::Arch; use gdbstub::common::Signal; +use gdbstub::target::ext::base::BaseOps; use gdbstub::target::ext::base::singlethread::{ SingleThreadBase, SingleThreadResume, SingleThreadResumeOps, SingleThreadSingleStep, SingleThreadSingleStepOps, }; -use gdbstub::target::ext::base::BaseOps; use gdbstub::target::ext::breakpoints::{ Breakpoints, BreakpointsOps, HwBreakpoint, HwBreakpointOps, SwBreakpoint, SwBreakpointOps, }; diff --git a/src/hyperlight_host/src/hypervisor/handlers.rs b/src/hyperlight_host/src/hypervisor/handlers.rs index 3ffd64441..f4234298c 100644 --- a/src/hyperlight_host/src/hypervisor/handlers.rs +++ b/src/hyperlight_host/src/hypervisor/handlers.rs @@ -16,9 +16,9 @@ limitations under the License. use std::sync::{Arc, Mutex}; -use tracing::{instrument, Span}; +use tracing::{Span, instrument}; -use crate::{new_error, Result}; +use crate::{Result, new_error}; /// The trait representing custom logic to handle the case when /// a Hypervisor's virtual CPU (vCPU) informs Hyperlight the guest diff --git a/src/hyperlight_host/src/hypervisor/hyperv_linux.rs b/src/hyperlight_host/src/hypervisor/hyperv_linux.rs index fbbeff222..ad57148f1 100644 --- a/src/hyperlight_host/src/hypervisor/hyperv_linux.rs +++ b/src/hyperlight_host/src/hypervisor/hyperv_linux.rs @@ -30,10 +30,10 @@ use log::error; #[cfg(mshv2)] use mshv_bindings::hv_message; use mshv_bindings::{ - hv_message_type, hv_message_type_HVMSG_GPA_INTERCEPT, hv_message_type_HVMSG_UNMAPPED_GPA, + FloatingPointUnit, SegmentRegister, SpecialRegisters, StandardRegisters, hv_message_type, + hv_message_type_HVMSG_GPA_INTERCEPT, hv_message_type_HVMSG_UNMAPPED_GPA, hv_message_type_HVMSG_X64_HALT, hv_message_type_HVMSG_X64_IO_PORT_INTERCEPT, hv_register_assoc, hv_register_name_HV_X64_REGISTER_RIP, hv_register_value, mshv_user_mem_region, - FloatingPointUnit, SegmentRegister, SpecialRegisters, StandardRegisters, }; #[cfg(mshv3)] use mshv_bindings::{ @@ -41,21 +41,21 @@ use mshv_bindings::{ hv_partition_synthetic_processor_features, }; use mshv_ioctls::{Mshv, VcpuFd, VmFd}; -use tracing::{instrument, Span}; +use tracing::{Span, instrument}; use super::fpu::{FP_CONTROL_WORD_DEFAULT, FP_TAG_WORD_DEFAULT, MXCSR_DEFAULT}; #[cfg(gdb)] use super::handlers::DbgMemAccessHandlerWrapper; use super::handlers::{MemAccessHandlerWrapper, OutBHandlerWrapper}; use super::{ - Hypervisor, VirtualCPU, CR0_AM, CR0_ET, CR0_MP, CR0_NE, CR0_PE, CR0_PG, CR0_WP, CR4_OSFXSR, - CR4_OSXMMEXCPT, CR4_PAE, EFER_LMA, EFER_LME, EFER_NX, EFER_SCE, + CR0_AM, CR0_ET, CR0_MP, CR0_NE, CR0_PE, CR0_PG, CR0_WP, CR4_OSFXSR, CR4_OSXMMEXCPT, CR4_PAE, + EFER_LMA, EFER_LME, EFER_NX, EFER_SCE, Hypervisor, VirtualCPU, }; -use crate::hypervisor::hypervisor_handler::HypervisorHandler; use crate::hypervisor::HyperlightExit; +use crate::hypervisor::hypervisor_handler::HypervisorHandler; use crate::mem::memory_region::{MemoryRegion, MemoryRegionFlags}; use crate::mem::ptr::{GuestPtr, RawPtr}; -use crate::{log_then_return, new_error, Result}; +use crate::{Result, log_then_return, new_error}; /// Determine whether the HyperV for Linux hypervisor API is present /// and functional. diff --git a/src/hyperlight_host/src/hypervisor/hyperv_windows.rs b/src/hyperlight_host/src/hypervisor/hyperv_windows.rs index 6b7c621b5..ccabdaed7 100644 --- a/src/hyperlight_host/src/hypervisor/hyperv_windows.rs +++ b/src/hyperlight_host/src/hypervisor/hyperv_windows.rs @@ -20,11 +20,11 @@ use std::fmt::{Debug, Formatter}; use std::string::String; use hyperlight_common::mem::PAGE_SIZE_USIZE; -use tracing::{instrument, Span}; +use tracing::{Span, instrument}; use windows::Win32::System::Hypervisor::{ - WHvX64RegisterCr0, WHvX64RegisterCr3, WHvX64RegisterCr4, WHvX64RegisterCs, WHvX64RegisterEfer, WHV_MEMORY_ACCESS_TYPE, WHV_PARTITION_HANDLE, WHV_REGISTER_VALUE, WHV_RUN_VP_EXIT_CONTEXT, WHV_RUN_VP_EXIT_REASON, WHV_X64_SEGMENT_REGISTER, WHV_X64_SEGMENT_REGISTER_0, + WHvX64RegisterCr0, WHvX64RegisterCr3, WHvX64RegisterCr4, WHvX64RegisterCs, WHvX64RegisterEfer, }; use super::fpu::{FP_TAG_WORD_DEFAULT, MXCSR_DEFAULT}; @@ -36,15 +36,15 @@ use super::surrogate_process_manager::*; use super::windows_hypervisor_platform::{VMPartition, VMProcessor}; use super::wrappers::{HandleWrapper, WHvFPURegisters}; use super::{ - HyperlightExit, Hypervisor, VirtualCPU, CR0_AM, CR0_ET, CR0_MP, CR0_NE, CR0_PE, CR0_PG, CR0_WP, - CR4_OSFXSR, CR4_OSXMMEXCPT, CR4_PAE, EFER_LMA, EFER_LME, EFER_NX, EFER_SCE, + CR0_AM, CR0_ET, CR0_MP, CR0_NE, CR0_PE, CR0_PG, CR0_WP, CR4_OSFXSR, CR4_OSXMMEXCPT, CR4_PAE, + EFER_LMA, EFER_LME, EFER_NX, EFER_SCE, HyperlightExit, Hypervisor, VirtualCPU, }; use crate::hypervisor::fpu::FP_CONTROL_WORD_DEFAULT; use crate::hypervisor::hypervisor_handler::HypervisorHandler; use crate::hypervisor::wrappers::WHvGeneralRegisters; use crate::mem::memory_region::{MemoryRegion, MemoryRegionFlags}; use crate::mem::ptr::{GuestPtr, RawPtr}; -use crate::{debug, new_error, Result}; +use crate::{Result, debug, new_error}; /// A Hypervisor driver for HyperV-on-Windows. pub(crate) struct HypervWindowsDriver { @@ -130,7 +130,7 @@ impl HypervWindowsDriver { WHV_REGISTER_VALUE { Segment: WHV_X64_SEGMENT_REGISTER { Anonymous: WHV_X64_SEGMENT_REGISTER_0 { - Attributes: 0b1011 | 1 << 4 | 1 << 7 | 1 << 13, // Type (11: Execute/Read, accessed) | L (64-bit mode) | P (present) | S (code segment) + Attributes: 0b1011 | (1 << 4) | (1 << 7) | (1 << 13), // Type (11: Execute/Read, accessed) | L (64-bit mode) | P (present) | S (code segment) }, ..Default::default() // zero out the rest }, @@ -491,9 +491,9 @@ pub mod tests { use serial_test::serial; + use crate::Result; use crate::hypervisor::handlers::{MemAccessHandler, OutBHandler}; use crate::hypervisor::tests::test_initialise; - use crate::Result; #[test] #[serial] diff --git a/src/hyperlight_host/src/hypervisor/hypervisor_handler.rs b/src/hyperlight_host/src/hypervisor/hypervisor_handler.rs index a66ebc608..20cb334a9 100644 --- a/src/hyperlight_host/src/hypervisor/hypervisor_handler.rs +++ b/src/hyperlight_host/src/hypervisor/hypervisor_handler.rs @@ -20,31 +20,35 @@ use std::ops::DerefMut; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, Mutex}; use std::thread; -use std::thread::{sleep, JoinHandle}; +use std::thread::{JoinHandle, sleep}; use std::time::Duration; #[cfg(target_os = "linux")] use crossbeam::atomic::AtomicCell; use crossbeam_channel::{Receiver, Sender}; #[cfg(target_os = "linux")] -use libc::{pthread_kill, pthread_self, ESRCH}; +use libc::{ESRCH, pthread_kill, pthread_self}; use log::{error, info}; -use tracing::{instrument, Span}; +use tracing::{Span, instrument}; #[cfg(target_os = "linux")] use vmm_sys_util::signal::SIGRTMIN; #[cfg(target_os = "windows")] -use windows::Win32::System::Hypervisor::{WHvCancelRunVirtualProcessor, WHV_PARTITION_HANDLE}; +use windows::Win32::System::Hypervisor::{WHV_PARTITION_HANDLE, WHvCancelRunVirtualProcessor}; #[cfg(gdb)] use super::gdb::create_gdb_thread; +use crate::HyperlightError::{ + GuestExecutionHungOnHostFunctionCall, + HypervisorHandlerExecutionCancelAttemptOnFinishedExecution, NoHypervisorFound, +}; #[cfg(feature = "function_call_metrics")] use crate::histogram_vec_observe; +use crate::hypervisor::Hypervisor; #[cfg(gdb)] use crate::hypervisor::handlers::DbgMemAccessHandlerWrapper; use crate::hypervisor::handlers::{MemAccessHandlerWrapper, OutBHandlerWrapper}; #[cfg(target_os = "windows")] use crate::hypervisor::wrappers::HandleWrapper; -use crate::hypervisor::Hypervisor; use crate::mem::layout::SandboxMemoryLayout; use crate::mem::mgr::SandboxMemoryManager; use crate::mem::ptr::{GuestPtr, RawPtr}; @@ -52,16 +56,12 @@ use crate::mem::ptr_offset::Offset; use crate::mem::shared_mem::{GuestSharedMemory, HostSharedMemory, SharedMemory}; #[cfg(gdb)] use crate::sandbox::config::DebugInfo; -use crate::sandbox::hypervisor::{get_available_hypervisor, HypervisorType}; +use crate::sandbox::hypervisor::{HypervisorType, get_available_hypervisor}; #[cfg(feature = "function_call_metrics")] use crate::sandbox::metrics::SandboxMetric::GuestFunctionCallDurationMicroseconds; #[cfg(target_os = "linux")] use crate::signal_handlers::setup_signal_handlers; -use crate::HyperlightError::{ - GuestExecutionHungOnHostFunctionCall, - HypervisorHandlerExecutionCancelAttemptOnFinishedExecution, NoHypervisorFound, -}; -use crate::{log_then_return, new_error, HyperlightError, Result}; +use crate::{HyperlightError, Result, log_then_return, new_error}; type HypervisorHandlerTx = Sender; type HypervisorHandlerRx = Receiver; @@ -985,15 +985,15 @@ mod tests { use hyperlight_common::flatbuffer_wrappers::function_types::{ParameterValue, ReturnType}; use hyperlight_testing::simple_guest_as_string; + use crate::HyperlightError::HypervisorHandlerExecutionCancelAttemptOnFinishedExecution; #[cfg(target_os = "windows")] use crate::sandbox::SandboxConfiguration; use crate::sandbox::WrapperGetter; use crate::sandbox_state::sandbox::EvolvableSandbox; use crate::sandbox_state::transition::Noop; - use crate::HyperlightError::HypervisorHandlerExecutionCancelAttemptOnFinishedExecution; use crate::{ - is_hypervisor_present, GuestBinary, HyperlightError, MultiUseSandbox, Result, - UninitializedSandbox, + GuestBinary, HyperlightError, MultiUseSandbox, Result, UninitializedSandbox, + is_hypervisor_present, }; fn create_multi_use_sandbox() -> MultiUseSandbox { diff --git a/src/hyperlight_host/src/hypervisor/inprocess.rs b/src/hyperlight_host/src/hypervisor/inprocess.rs index 1fec3df54..5d117624c 100644 --- a/src/hyperlight_host/src/hypervisor/inprocess.rs +++ b/src/hyperlight_host/src/hypervisor/inprocess.rs @@ -20,10 +20,10 @@ use std::os::raw::c_void; #[cfg(gdb)] use super::handlers::DbgMemAccessHandlerWrapper; use super::{HyperlightExit, Hypervisor}; +use crate::Result; #[cfg(crashdump)] use crate::mem::memory_region::MemoryRegion; use crate::sandbox::leaked_outb::LeakedOutBWrapper; -use crate::Result; /// Arguments passed to inprocess driver pub struct InprocessArgs<'a> { @@ -66,7 +66,7 @@ impl Debug for InprocessDriver<'_> { } } -impl<'a> Hypervisor for InprocessDriver<'a> { +impl Hypervisor for InprocessDriver<'_> { fn initialise( &mut self, _peb_addr: crate::mem::ptr::RawPtr, diff --git a/src/hyperlight_host/src/hypervisor/kvm.rs b/src/hyperlight_host/src/hypervisor/kvm.rs index 5d01ec8ac..18300c8f2 100644 --- a/src/hyperlight_host/src/hypervisor/kvm.rs +++ b/src/hyperlight_host/src/hypervisor/kvm.rs @@ -19,10 +19,10 @@ use std::fmt::Debug; #[cfg(gdb)] use std::sync::{Arc, Mutex}; -use kvm_bindings::{kvm_fpu, kvm_regs, kvm_userspace_memory_region, KVM_MEM_READONLY}; +use kvm_bindings::{KVM_MEM_READONLY, kvm_fpu, kvm_regs, kvm_userspace_memory_region}; use kvm_ioctls::Cap::UserMemory; use kvm_ioctls::{Kvm, VcpuExit, VcpuFd, VmFd}; -use tracing::{instrument, Span}; +use tracing::{Span, instrument}; use super::fpu::{FP_CONTROL_WORD_DEFAULT, FP_TAG_WORD_DEFAULT, MXCSR_DEFAULT}; #[cfg(gdb)] @@ -31,15 +31,15 @@ use super::gdb::{DebugCommChannel, DebugMsg, DebugResponse, VcpuStopReason}; use super::handlers::DbgMemAccessHandlerWrapper; use super::handlers::{MemAccessHandlerWrapper, OutBHandlerWrapper}; use super::{ - HyperlightExit, Hypervisor, VirtualCPU, CR0_AM, CR0_ET, CR0_MP, CR0_NE, CR0_PE, CR0_PG, CR0_WP, - CR4_OSFXSR, CR4_OSXMMEXCPT, CR4_PAE, EFER_LMA, EFER_LME, EFER_NX, EFER_SCE, + CR0_AM, CR0_ET, CR0_MP, CR0_NE, CR0_PE, CR0_PG, CR0_WP, CR4_OSFXSR, CR4_OSXMMEXCPT, CR4_PAE, + EFER_LMA, EFER_LME, EFER_NX, EFER_SCE, HyperlightExit, Hypervisor, VirtualCPU, }; +#[cfg(gdb)] +use crate::HyperlightError; use crate::hypervisor::hypervisor_handler::HypervisorHandler; use crate::mem::memory_region::{MemoryRegion, MemoryRegionFlags}; use crate::mem::ptr::{GuestPtr, RawPtr}; -#[cfg(gdb)] -use crate::HyperlightError; -use crate::{log_then_return, new_error, Result}; +use crate::{Result, log_then_return, new_error}; /// Return `true` if the KVM API is available, version 12, and has UserMemory capability, or `false` otherwise #[instrument(skip_all, parent = Span::current(), level = "Trace")] @@ -70,8 +70,8 @@ mod debug { use hyperlight_common::mem::PAGE_SIZE; use kvm_bindings::{ - kvm_guest_debug, kvm_regs, KVM_GUESTDBG_ENABLE, KVM_GUESTDBG_SINGLESTEP, - KVM_GUESTDBG_USE_HW_BP, KVM_GUESTDBG_USE_SW_BP, + KVM_GUESTDBG_ENABLE, KVM_GUESTDBG_SINGLESTEP, KVM_GUESTDBG_USE_HW_BP, + KVM_GUESTDBG_USE_SW_BP, kvm_guest_debug, kvm_regs, }; use kvm_ioctls::VcpuFd; @@ -79,7 +79,7 @@ mod debug { use crate::hypervisor::gdb::{DebugMsg, DebugResponse, VcpuStopReason, X86_64Regs}; use crate::hypervisor::handlers::DbgMemAccessHandlerCaller; use crate::mem::layout::SandboxMemoryLayout; - use crate::{new_error, HyperlightError, Result}; + use crate::{HyperlightError, Result, new_error}; /// Software Breakpoint size in memory pub const SW_BP_SIZE: usize = 1; @@ -923,11 +923,11 @@ impl Hypervisor for KVMDriver { mod tests { use std::sync::{Arc, Mutex}; + use crate::Result; #[cfg(gdb)] use crate::hypervisor::handlers::DbgMemAccessHandlerCaller; use crate::hypervisor::handlers::{MemAccessHandler, OutBHandler}; use crate::hypervisor::tests::test_initialise; - use crate::Result; #[cfg(gdb)] struct DbgMemAccessHandler {} diff --git a/src/hyperlight_host/src/hypervisor/metrics.rs b/src/hyperlight_host/src/hypervisor/metrics.rs index a02d19ed0..a34b23209 100644 --- a/src/hyperlight_host/src/hypervisor/metrics.rs +++ b/src/hyperlight_host/src/hypervisor/metrics.rs @@ -22,7 +22,7 @@ use std::sync::Once; use once_cell::sync::OnceCell; use strum::{EnumIter, IntoStaticStr, VariantNames}; -use tracing::{instrument, Span}; +use tracing::{Span, instrument}; use crate::metrics::{ HyperlightMetric, HyperlightMetricDefinition, HyperlightMetricEnum, HyperlightMetricType, diff --git a/src/hyperlight_host/src/hypervisor/mod.rs b/src/hyperlight_host/src/hypervisor/mod.rs index 929aff0ab..8495677af 100644 --- a/src/hyperlight_host/src/hypervisor/mod.rs +++ b/src/hyperlight_host/src/hypervisor/mod.rs @@ -14,12 +14,12 @@ See the License for the specific language governing permissions and limitations under the License. */ -use tracing::{instrument, Span}; +use tracing::{Span, instrument}; use crate::error::HyperlightError::ExecutionCanceledByHost; use crate::hypervisor::metrics::HypervisorMetric::NumberOfCancelledGuestExecutions; use crate::mem::memory_region::{MemoryRegion, MemoryRegionFlags}; -use crate::{int_counter_inc, log_then_return, new_error, HyperlightError, Result}; +use crate::{HyperlightError, Result, int_counter_inc, log_then_return, new_error}; /// Util for handling x87 fpu state #[cfg(any(kvm, mshv, target_os = "windows"))] @@ -318,7 +318,7 @@ pub(crate) mod tests { use crate::mem::ptr::RawPtr; use crate::sandbox::uninitialized::GuestBinary; use crate::sandbox::{SandboxConfiguration, UninitializedSandbox}; - use crate::{new_error, Result}; + use crate::{Result, new_error}; pub(crate) fn test_initialise( outb_hdl: OutBHandlerWrapper, diff --git a/src/hyperlight_host/src/hypervisor/surrogate_process.rs b/src/hyperlight_host/src/hypervisor/surrogate_process.rs index 4ebbaec94..6ff2bb33c 100644 --- a/src/hyperlight_host/src/hypervisor/surrogate_process.rs +++ b/src/hyperlight_host/src/hypervisor/surrogate_process.rs @@ -16,10 +16,10 @@ limitations under the License. use core::ffi::c_void; -use tracing::{instrument, Span}; +use tracing::{Span, instrument}; use windows::Win32::Foundation::HANDLE; use windows::Win32::System::Memory::{ - UnmapViewOfFile2, MEMORY_MAPPED_VIEW_ADDRESS, UNMAP_VIEW_OF_FILE_FLAGS, + MEMORY_MAPPED_VIEW_ADDRESS, UNMAP_VIEW_OF_FILE_FLAGS, UnmapViewOfFile2, }; use super::surrogate_process_manager::get_surrogate_process_manager; @@ -78,7 +78,10 @@ impl Drop for SurrogateProcess { Ok(manager) => match manager.return_surrogate_process(self.process_handle) { Ok(_) => (), Err(e) => { - tracing::error!("Failed to return surrogate process to surrogate process manager when dropping : {:?}", e); + tracing::error!( + "Failed to return surrogate process to surrogate process manager when dropping : {:?}", + e + ); return; } }, diff --git a/src/hyperlight_host/src/hypervisor/surrogate_process_manager.rs b/src/hyperlight_host/src/hypervisor/surrogate_process_manager.rs index ebfe28c06..781fec5da 100644 --- a/src/hyperlight_host/src/hypervisor/surrogate_process_manager.rs +++ b/src/hyperlight_host/src/hypervisor/surrogate_process_manager.rs @@ -20,30 +20,30 @@ use std::io::Write; use std::mem::size_of; use std::path::{Path, PathBuf}; -use crossbeam_channel::{unbounded, Receiver, Sender}; +use crossbeam_channel::{Receiver, Sender, unbounded}; use hyperlight_common::mem::PAGE_SIZE_USIZE; use rust_embed::RustEmbed; -use tracing::{info, instrument, Span}; -use windows::core::{s, PCSTR}; +use tracing::{Span, info, instrument}; use windows::Win32::Foundation::HANDLE; use windows::Win32::Security::SECURITY_ATTRIBUTES; use windows::Win32::System::JobObjects::{ - AssignProcessToJobObject, CreateJobObjectA, JobObjectExtendedLimitInformation, - SetInformationJobObject, TerminateJobObject, JOBOBJECT_BASIC_LIMIT_INFORMATION, - JOBOBJECT_EXTENDED_LIMIT_INFORMATION, JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE, + AssignProcessToJobObject, CreateJobObjectA, JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE, + JOBOBJECT_BASIC_LIMIT_INFORMATION, JOBOBJECT_EXTENDED_LIMIT_INFORMATION, + JobObjectExtendedLimitInformation, SetInformationJobObject, TerminateJobObject, }; use windows::Win32::System::Memory::{ - MapViewOfFileNuma2, VirtualProtectEx, PAGE_NOACCESS, PAGE_PROTECTION_FLAGS, PAGE_READWRITE, + MapViewOfFileNuma2, PAGE_NOACCESS, PAGE_PROTECTION_FLAGS, PAGE_READWRITE, VirtualProtectEx, }; use windows::Win32::System::SystemServices::NUMA_NO_PREFERRED_NODE; use windows::Win32::System::Threading::{ - CreateProcessA, CREATE_SUSPENDED, PROCESS_INFORMATION, STARTUPINFOA, + CREATE_SUSPENDED, CreateProcessA, PROCESS_INFORMATION, STARTUPINFOA, }; +use windows::core::{PCSTR, s}; use super::surrogate_process::SurrogateProcess; use super::wrappers::{HandleWrapper, PSTRWrapper}; use crate::HyperlightError::WindowsAPIError; -use crate::{log_then_return, new_error, Result}; +use crate::{Result, log_then_return, new_error}; // Use the rust-embed crate to embed the hyperlights_surrogate.exe // binary in the hyperlight-host library to make dependency management easier. @@ -415,16 +415,16 @@ mod tests { use std::time::{Duration, Instant}; use hyperlight_common::mem::PAGE_SIZE_USIZE; - use rand::{rng, Rng}; + use rand::{Rng, rng}; use serial_test::serial; - use windows::Win32::Foundation::{CloseHandle, BOOL, HANDLE, INVALID_HANDLE_VALUE}; + use windows::Win32::Foundation::{BOOL, CloseHandle, HANDLE, INVALID_HANDLE_VALUE}; use windows::Win32::System::Diagnostics::ToolHelp::{ - CreateToolhelp32Snapshot, Process32First, Process32Next, PROCESSENTRY32, TH32CS_SNAPPROCESS, + CreateToolhelp32Snapshot, PROCESSENTRY32, Process32First, Process32Next, TH32CS_SNAPPROCESS, }; use windows::Win32::System::JobObjects::IsProcessInJob; use windows::Win32::System::Memory::{ - CreateFileMappingA, MapViewOfFile, UnmapViewOfFile, FILE_MAP_ALL_ACCESS, PAGE_READWRITE, - SEC_COMMIT, + CreateFileMappingA, FILE_MAP_ALL_ACCESS, MapViewOfFile, PAGE_READWRITE, SEC_COMMIT, + UnmapViewOfFile, }; use super::*; diff --git a/src/hyperlight_host/src/hypervisor/windows_hypervisor_platform.rs b/src/hyperlight_host/src/hypervisor/windows_hypervisor_platform.rs index 18eda5f23..da56bc097 100644 --- a/src/hyperlight_host/src/hypervisor/windows_hypervisor_platform.rs +++ b/src/hyperlight_host/src/hypervisor/windows_hypervisor_platform.rs @@ -16,17 +16,17 @@ limitations under the License. use core::ffi::c_void; -use tracing::{instrument, Span}; -use windows::core::s; +use tracing::{Span, instrument}; use windows::Win32::Foundation::{FreeLibrary, HANDLE}; use windows::Win32::System::Hypervisor::*; use windows::Win32::System::LibraryLoader::*; +use windows::core::s; use windows_result::HRESULT; use super::wrappers::HandleWrapper; use crate::hypervisor::wrappers::{WHvFPURegisters, WHvGeneralRegisters, WHvSpecialRegisters}; use crate::mem::memory_region::{MemoryRegion, MemoryRegionFlags}; -use crate::{new_error, Result}; +use crate::{Result, new_error}; // We need to pass in a primitive array of register names/values // to WHvSetVirtualProcessorRegisters and rust needs to know array size diff --git a/src/hyperlight_host/src/hypervisor/wrappers.rs b/src/hyperlight_host/src/hypervisor/wrappers.rs index aa9943d6a..ae017f00e 100644 --- a/src/hyperlight_host/src/hypervisor/wrappers.rs +++ b/src/hyperlight_host/src/hypervisor/wrappers.rs @@ -16,10 +16,10 @@ limitations under the License. use std::ffi::CString; -use tracing::{instrument, Span}; -use windows::core::PSTR; +use tracing::{Span, instrument}; use windows::Win32::Foundation::{HANDLE, HMODULE}; use windows::Win32::System::Hypervisor::WHV_REGISTER_VALUE; +use windows::core::PSTR; use crate::{HyperlightError, Result}; diff --git a/src/hyperlight_host/src/lib.rs b/src/hyperlight_host/src/lib.rs index 5921889d6..3558c2a3b 100644 --- a/src/hyperlight_host/src/lib.rs +++ b/src/hyperlight_host/src/lib.rs @@ -90,10 +90,6 @@ pub(crate) mod testing; pub use error::HyperlightError; /// The re-export for the set_registry function pub use metrics::set_metrics_registry; -/// The re-export for the `is_hypervisor_present` type -pub use sandbox::is_hypervisor_present; -/// The re-export for the `GuestBinary` type -pub use sandbox::uninitialized::GuestBinary; /// Re-export for `HypervisorWrapper` trait /// Re-export for `MemMgrWrapper` type /// A sandbox that can call be used to make multiple calls to guest functions, @@ -103,6 +99,10 @@ pub use sandbox::MultiUseSandbox; pub use sandbox::SandboxRunOptions; /// The re-export for the `UninitializedSandbox` type pub use sandbox::UninitializedSandbox; +/// The re-export for the `is_hypervisor_present` type +pub use sandbox::is_hypervisor_present; +/// The re-export for the `GuestBinary` type +pub use sandbox::uninitialized::GuestBinary; /// The re-export for the `MultiUseGuestCallContext` type` pub use crate::func::call_ctx::MultiUseGuestCallContext; diff --git a/src/hyperlight_host/src/mem/custom_drop.rs b/src/hyperlight_host/src/mem/custom_drop.rs index 822632af0..2de1c6e01 100644 --- a/src/hyperlight_host/src/mem/custom_drop.rs +++ b/src/hyperlight_host/src/mem/custom_drop.rs @@ -16,7 +16,7 @@ limitations under the License. use std::fmt::Debug; -use tracing::{instrument, Span}; +use tracing::{Span, instrument}; /// A struct that stores a `*mut EltT` and allows the creator of the struct /// to specify the functionality to be run when the struct is dropped. @@ -33,7 +33,7 @@ pub(crate) struct CustomPtrDrop<'a, EltT> { drop: Box, } -impl<'a, EltT> CustomPtrDrop<'a, EltT> { +impl CustomPtrDrop<'_, EltT> { #[instrument(skip_all, parent = Span::current(), level= "Trace")] pub(crate) fn new(elt: *mut EltT, drop_fn: Box) -> Self { Self { @@ -47,13 +47,13 @@ impl<'a, EltT> CustomPtrDrop<'a, EltT> { } } -impl<'a, EltT> Debug for CustomPtrDrop<'a, EltT> { +impl Debug for CustomPtrDrop<'_, EltT> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("CustomDrop").finish() } } -impl<'a, EltT> Drop for CustomPtrDrop<'a, EltT> { +impl Drop for CustomPtrDrop<'_, EltT> { #[instrument(skip_all, parent = Span::current(), level= "Trace")] fn drop(&mut self) { let drop_fn = &self.drop; diff --git a/src/hyperlight_host/src/mem/elf.rs b/src/hyperlight_host/src/mem/elf.rs index ec1918323..44d95e946 100644 --- a/src/hyperlight_host/src/mem/elf.rs +++ b/src/hyperlight_host/src/mem/elf.rs @@ -21,7 +21,7 @@ use goblin::elf::reloc::{R_X86_64_NONE, R_X86_64_RELATIVE}; use goblin::elf::{Elf, ProgramHeaders, Reloc}; use goblin::elf64::program_header::PT_LOAD; -use crate::{log_then_return, new_error, Result}; +use crate::{Result, log_then_return, new_error}; pub(crate) struct ElfInfo { payload: Vec, diff --git a/src/hyperlight_host/src/mem/layout.rs b/src/hyperlight_host/src/mem/layout.rs index 3a13879c4..040f14aba 100644 --- a/src/hyperlight_host/src/mem/layout.rs +++ b/src/hyperlight_host/src/mem/layout.rs @@ -16,10 +16,10 @@ limitations under the License. use std::fmt::Debug; use std::mem::{offset_of, size_of}; -use hyperlight_common::mem::{GuestStackData, HyperlightPEB, RunMode, PAGE_SIZE_USIZE}; +use hyperlight_common::mem::{GuestStackData, HyperlightPEB, PAGE_SIZE_USIZE, RunMode}; use paste::paste; -use rand::{rng, RngCore}; -use tracing::{instrument, Span}; +use rand::{RngCore, rng}; +use tracing::{Span, instrument}; use super::memory_region::MemoryRegionType::{ BootStack, Code, GuardPage, GuestErrorData, Heap, HostExceptionData, HostFunctionDefinitions, @@ -30,7 +30,7 @@ use super::mgr::AMOUNT_OF_MEMORY_PER_PT; use super::shared_mem::{ExclusiveSharedMemory, GuestSharedMemory, SharedMemory}; use crate::error::HyperlightError::{GuestOffsetIsInvalid, MemoryRequestTooBig}; use crate::sandbox::SandboxConfiguration; -use crate::{log_then_return, new_error, Result}; +use crate::{Result, log_then_return, new_error}; // +-------------------------------------------+ // | Boot Stack (4KiB) | @@ -739,8 +739,7 @@ impl SandboxMemoryLayout { // Get the number of pages needed for the PTs - let num_pages: usize = ((total_mapped_memory_size + AMOUNT_OF_MEMORY_PER_PT - 1) - / AMOUNT_OF_MEMORY_PER_PT) + let num_pages: usize = total_mapped_memory_size.div_ceil(AMOUNT_OF_MEMORY_PER_PT) + 1 // Round up + 3; // PML4, PDPT, PD diff --git a/src/hyperlight_host/src/mem/loaded_lib.rs b/src/hyperlight_host/src/mem/loaded_lib.rs index f579d2e13..692273745 100644 --- a/src/hyperlight_host/src/mem/loaded_lib.rs +++ b/src/hyperlight_host/src/mem/loaded_lib.rs @@ -18,15 +18,15 @@ use std::ffi::OsStr; use std::os::windows::ffi::OsStrExt; use std::sync::{Arc, Mutex, Weak}; -use tracing::{instrument, Span}; -use windows::core::PCWSTR; +use tracing::{Span, instrument}; use windows::Win32::Foundation::HMODULE; use windows::Win32::System::LibraryLoader::LoadLibraryW; +use windows::core::PCWSTR; use windows_sys::Win32::Foundation::FreeLibrary; use super::ptr::RawPtr; use crate::hypervisor::wrappers::HModuleWrapper; -use crate::{log_then_return, Result}; +use crate::{Result, log_then_return}; /// A wrapper around a binary loaded with the Windows /// [`LoadLibraryW`](https://microsoft.github.io/windows-docs-rs/doc/windows/Win32/System/LibraryLoader/fn.LoadLibraryW.html) diff --git a/src/hyperlight_host/src/mem/memory_region.rs b/src/hyperlight_host/src/mem/memory_region.rs index 6956d9635..fdd4ca8a7 100644 --- a/src/hyperlight_host/src/mem/memory_region.rs +++ b/src/hyperlight_host/src/mem/memory_region.rs @@ -30,8 +30,6 @@ use bitflags::bitflags; #[cfg(mshv)] use hyperlight_common::mem::PAGE_SHIFT; use hyperlight_common::mem::PAGE_SIZE_USIZE; -#[cfg(mshv)] -use mshv_bindings::{hv_x64_memory_intercept_message, mshv_user_mem_region}; #[cfg(mshv2)] use mshv_bindings::{ HV_MAP_GPA_EXECUTABLE, HV_MAP_GPA_PERMISSIONS_NONE, HV_MAP_GPA_READABLE, HV_MAP_GPA_WRITABLE, @@ -40,6 +38,8 @@ use mshv_bindings::{ use mshv_bindings::{ MSHV_SET_MEM_BIT_EXECUTABLE, MSHV_SET_MEM_BIT_UNMAP, MSHV_SET_MEM_BIT_WRITABLE, }; +#[cfg(mshv)] +use mshv_bindings::{hv_x64_memory_intercept_message, mshv_user_mem_region}; #[cfg(target_os = "windows")] use windows::Win32::System::Hypervisor::{self, WHV_MEMORY_ACCESS_TYPE}; diff --git a/src/hyperlight_host/src/mem/mgr.rs b/src/hyperlight_host/src/mem/mgr.rs index 993f68679..45057aa82 100644 --- a/src/hyperlight_host/src/mem/mgr.rs +++ b/src/hyperlight_host/src/mem/mgr.rs @@ -20,14 +20,14 @@ use std::str::from_utf8; use std::sync::{Arc, Mutex}; use hyperlight_common::flatbuffer_wrappers::function_call::{ - validate_guest_function_call_buffer, FunctionCall, + FunctionCall, validate_guest_function_call_buffer, }; use hyperlight_common::flatbuffer_wrappers::function_types::ReturnValue; use hyperlight_common::flatbuffer_wrappers::guest_error::{ErrorCode, GuestError}; use hyperlight_common::flatbuffer_wrappers::guest_log_data::GuestLogData; use hyperlight_common::flatbuffer_wrappers::host_function_details::HostFunctionDetails; use serde_json::from_str; -use tracing::{instrument, Span}; +use tracing::{Span, instrument}; use super::exe::ExeInfo; use super::layout::SandboxMemoryLayout; @@ -44,7 +44,7 @@ use crate::error::HyperlightError::{ }; use crate::error::HyperlightHostError; use crate::sandbox::SandboxConfiguration; -use crate::{log_then_return, new_error, HyperlightError, Result}; +use crate::{HyperlightError, Result, log_then_return, new_error}; /// Paging Flags /// @@ -181,8 +181,7 @@ where let mem_size = usize::try_from(mem_size)?; - let num_pages: usize = - ((mem_size + AMOUNT_OF_MEMORY_PER_PT - 1) / AMOUNT_OF_MEMORY_PER_PT) + 1; + let num_pages: usize = mem_size.div_ceil(AMOUNT_OF_MEMORY_PER_PT) + 1; // Create num_pages PT with 512 PTEs for p in 0..num_pages { @@ -882,9 +881,10 @@ mod tests { panic!("loadlib with elf should fail"); } Err(err) => { - assert!(err - .to_string() - .contains("LoadLibrary can only be used with PE files")); + assert!( + err.to_string() + .contains("LoadLibrary can only be used with PE files") + ); } } } diff --git a/src/hyperlight_host/src/mem/pe/base_relocations.rs b/src/hyperlight_host/src/mem/pe/base_relocations.rs index 6dec8fb34..6012e86f8 100644 --- a/src/hyperlight_host/src/mem/pe/base_relocations.rs +++ b/src/hyperlight_host/src/mem/pe/base_relocations.rs @@ -16,7 +16,7 @@ limitations under the License. use goblin::error; use goblin::pe::section_table::SectionTable; -use tracing::{instrument, Span}; +use tracing::{Span, instrument}; use crate::Result; @@ -71,7 +71,7 @@ impl<'a> BaseRelocations<'a> { } } -impl<'a> Iterator for BaseRelocations<'a> { +impl Iterator for BaseRelocations<'_> { type Item = BaseRelocation; fn next(&mut self) -> Option { // Check if we can read 2 bytes from the array diff --git a/src/hyperlight_host/src/mem/pe/pe_info.rs b/src/hyperlight_host/src/mem/pe/pe_info.rs index ae8ea3ed9..464095636 100644 --- a/src/hyperlight_host/src/mem/pe/pe_info.rs +++ b/src/hyperlight_host/src/mem/pe/pe_info.rs @@ -17,13 +17,13 @@ limitations under the License. use std::io::{Cursor, Read, Write}; use std::{iter, mem}; +use goblin::pe::PE; use goblin::pe::optional_header::OptionalHeader; use goblin::pe::section_table::SectionTable; -use goblin::pe::PE; -use tracing::{instrument, Span}; +use tracing::{Span, instrument}; use crate::mem::pe::base_relocations; -use crate::{log_then_return, Result}; +use crate::{Result, log_then_return}; const IMAGE_REL_BASED_DIR64: u8 = 10; const IMAGE_REL_BASED_ABSOLUTE: u8 = 0; @@ -81,7 +81,9 @@ impl PEInfo { if optional_header.windows_fields.section_alignment != optional_header.windows_fields.file_alignment { - log_then_return!("unsupported PE file, section alignment does not match file alignment make sure to link the .exe with /FILEALIGN and /ALIGN options set to the same value") + log_then_return!( + "unsupported PE file, section alignment does not match file alignment make sure to link the .exe with /FILEALIGN and /ALIGN options set to the same value" + ) } if (pe.header.coff_header.characteristics & CHARACTERISTICS_RELOCS_STRIPPED) @@ -340,7 +342,7 @@ mod tests { use hyperlight_testing::{callback_guest_exe_as_string, simple_guest_exe_as_string}; use crate::mem::exe::ExeInfo; - use crate::{new_error, Result}; + use crate::{Result, new_error}; #[allow(dead_code)] struct PEFileTest { diff --git a/src/hyperlight_host/src/mem/ptr.rs b/src/hyperlight_host/src/mem/ptr.rs index bacab051c..f830081d1 100644 --- a/src/hyperlight_host/src/mem/ptr.rs +++ b/src/hyperlight_host/src/mem/ptr.rs @@ -16,12 +16,12 @@ limitations under the License. use std::ops::Add; -use tracing::{instrument, Span}; +use tracing::{Span, instrument}; use super::ptr_addr_space::{AddressSpace, GuestAddressSpace}; use super::ptr_offset::Offset; -use crate::error::HyperlightError::{self, CheckedAddOverflow, RawPointerLessThanBaseAddress}; use crate::Result; +use crate::error::HyperlightError::{self, CheckedAddOverflow, RawPointerLessThanBaseAddress}; /// A representation of a raw pointer inside a given address space. /// diff --git a/src/hyperlight_host/src/mem/ptr_addr_space.rs b/src/hyperlight_host/src/mem/ptr_addr_space.rs index 3f84549a7..d3e73ebb4 100644 --- a/src/hyperlight_host/src/mem/ptr_addr_space.rs +++ b/src/hyperlight_host/src/mem/ptr_addr_space.rs @@ -14,7 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ -use tracing::{instrument, Span}; +use tracing::{Span, instrument}; use super::layout::SandboxMemoryLayout; use crate::Result; diff --git a/src/hyperlight_host/src/mem/ptr_offset.rs b/src/hyperlight_host/src/mem/ptr_offset.rs index 3e4654b9a..b87d4d204 100644 --- a/src/hyperlight_host/src/mem/ptr_offset.rs +++ b/src/hyperlight_host/src/mem/ptr_offset.rs @@ -18,10 +18,10 @@ use std::cmp::{Eq, Ord, Ordering, PartialEq, PartialOrd}; use std::convert::From; use std::ops::{Add, Sub}; -use tracing::{instrument, Span}; +use tracing::{Span, instrument}; -use crate::error::HyperlightError; use crate::Result; +use crate::error::HyperlightError; /// An offset into a given address space. /// diff --git a/src/hyperlight_host/src/mem/shared_mem.rs b/src/hyperlight_host/src/mem/shared_mem.rs index 721704b41..c53b36b78 100644 --- a/src/hyperlight_host/src/mem/shared_mem.rs +++ b/src/hyperlight_host/src/mem/shared_mem.rs @@ -22,9 +22,7 @@ use std::ptr::null_mut; use std::sync::{Arc, RwLock}; use hyperlight_common::mem::PAGE_SIZE_USIZE; -use tracing::{instrument, Span}; -#[cfg(target_os = "windows")] -use windows::core::PCSTR; +use tracing::{Span, instrument}; #[cfg(target_os = "windows")] use windows::Win32::Foundation::{CloseHandle, HANDLE, INVALID_HANDLE_VALUE}; #[cfg(all(target_os = "windows", inprocess))] @@ -33,15 +31,17 @@ use windows::Win32::System::Memory::FILE_MAP_EXECUTE; use windows::Win32::System::Memory::PAGE_READWRITE; #[cfg(target_os = "windows")] use windows::Win32::System::Memory::{ - CreateFileMappingA, MapViewOfFile, UnmapViewOfFile, VirtualProtect, FILE_MAP_ALL_ACCESS, - MEMORY_MAPPED_VIEW_ADDRESS, PAGE_EXECUTE_READWRITE, PAGE_NOACCESS, PAGE_PROTECTION_FLAGS, + CreateFileMappingA, FILE_MAP_ALL_ACCESS, MEMORY_MAPPED_VIEW_ADDRESS, MapViewOfFile, + PAGE_EXECUTE_READWRITE, PAGE_NOACCESS, PAGE_PROTECTION_FLAGS, UnmapViewOfFile, VirtualProtect, }; +#[cfg(target_os = "windows")] +use windows::core::PCSTR; #[cfg(target_os = "windows")] use crate::HyperlightError::MemoryAllocationFailed; #[cfg(target_os = "windows")] use crate::HyperlightError::{MemoryRequestTooBig, WindowsAPIError}; -use crate::{log_then_return, new_error, Result}; +use crate::{Result, log_then_return, new_error}; /// Makes sure that the given `offset` and `size` are within the bounds of the memory with size `mem_size`. macro_rules! bounds_check { @@ -314,8 +314,8 @@ impl ExclusiveSharedMemory { #[instrument(skip_all, parent = Span::current(), level= "Trace")] pub fn new(min_size_bytes: usize) -> Result { use libc::{ - c_int, mmap, mprotect, off_t, size_t, MAP_ANONYMOUS, MAP_FAILED, MAP_NORESERVE, - MAP_SHARED, PROT_NONE, PROT_READ, PROT_WRITE, + MAP_ANONYMOUS, MAP_FAILED, MAP_NORESERVE, MAP_SHARED, PROT_NONE, PROT_READ, PROT_WRITE, + c_int, mmap, mprotect, off_t, size_t, }; use crate::error::HyperlightError::{MemoryRequestTooBig, MmapFailed, MprotectFailed}; @@ -528,7 +528,7 @@ impl ExclusiveSharedMemory { // make the memory executable on Linux #[cfg(target_os = "linux")] { - use libc::{mprotect, PROT_EXEC, PROT_READ, PROT_WRITE}; + use libc::{PROT_EXEC, PROT_READ, PROT_WRITE, mprotect}; let res = unsafe { mprotect( @@ -1016,8 +1016,8 @@ mod tests { use proptest::prelude::*; use super::{ExclusiveSharedMemory, HostSharedMemory, SharedMemory}; - use crate::mem::shared_mem_tests::read_write_test_suite; use crate::Result; + use crate::mem::shared_mem_tests::read_write_test_suite; #[test] fn fill() { diff --git a/src/hyperlight_host/src/mem/shared_mem_snapshot.rs b/src/hyperlight_host/src/mem/shared_mem_snapshot.rs index 28d514b76..b2de715ee 100644 --- a/src/hyperlight_host/src/mem/shared_mem_snapshot.rs +++ b/src/hyperlight_host/src/mem/shared_mem_snapshot.rs @@ -14,7 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ -use tracing::{instrument, Span}; +use tracing::{Span, instrument}; use super::shared_mem::SharedMemory; use crate::Result; diff --git a/src/hyperlight_host/src/mem/shared_mem_tests.rs b/src/hyperlight_host/src/mem/shared_mem_tests.rs index 44c54bd03..205c434b7 100644 --- a/src/hyperlight_host/src/mem/shared_mem_tests.rs +++ b/src/hyperlight_host/src/mem/shared_mem_tests.rs @@ -22,7 +22,7 @@ use std::mem::size_of; use hyperlight_common::mem::PAGE_SIZE_USIZE; -use crate::{log_then_return, new_error, Result}; +use crate::{Result, log_then_return, new_error}; /// A function that knows how to read data of type `T` from a /// `SharedMemory` at a specified offset diff --git a/src/hyperlight_host/src/metrics/histogram.rs b/src/hyperlight_host/src/metrics/histogram.rs index 82ddefdfa..375a2d12b 100644 --- a/src/hyperlight_host/src/metrics/histogram.rs +++ b/src/hyperlight_host/src/metrics/histogram.rs @@ -14,14 +14,14 @@ See the License for the specific language governing permissions and limitations under the License. */ -use prometheus::{register_histogram_with_registry, Histogram as PHistogram}; -use tracing::{instrument, Span}; +use prometheus::{Histogram as PHistogram, register_histogram_with_registry}; +use tracing::{Span, instrument}; use super::{ - get_histogram_opts, get_metrics_registry, GetHyperlightMetric, HyperlightMetric, - HyperlightMetricOps, + GetHyperlightMetric, HyperlightMetric, HyperlightMetricOps, get_histogram_opts, + get_metrics_registry, }; -use crate::{new_error, HyperlightError, Result}; +use crate::{HyperlightError, Result, new_error}; /// A named histogram #[derive(Debug)] diff --git a/src/hyperlight_host/src/metrics/histogram_vec.rs b/src/hyperlight_host/src/metrics/histogram_vec.rs index 0c4ff9141..cfeffe7ca 100644 --- a/src/hyperlight_host/src/metrics/histogram_vec.rs +++ b/src/hyperlight_host/src/metrics/histogram_vec.rs @@ -14,14 +14,14 @@ See the License for the specific language governing permissions and limitations under the License. */ -use prometheus::{register_histogram_vec_with_registry, HistogramVec as PHistogramVec}; -use tracing::{instrument, Span}; +use prometheus::{HistogramVec as PHistogramVec, register_histogram_vec_with_registry}; +use tracing::{Span, instrument}; use super::{ - get_histogram_opts, get_metrics_registry, GetHyperlightMetric, HyperlightMetric, - HyperlightMetricOps, + GetHyperlightMetric, HyperlightMetric, HyperlightMetricOps, get_histogram_opts, + get_metrics_registry, }; -use crate::{new_error, HyperlightError, Result}; +use crate::{HyperlightError, Result, new_error}; /// A named bundle of histograms #[derive(Debug)] diff --git a/src/hyperlight_host/src/metrics/int_counter.rs b/src/hyperlight_host/src/metrics/int_counter.rs index b164f50ca..9b7de0ab1 100644 --- a/src/hyperlight_host/src/metrics/int_counter.rs +++ b/src/hyperlight_host/src/metrics/int_counter.rs @@ -16,13 +16,13 @@ limitations under the License. use prometheus::core::{AtomicU64, GenericCounter}; use prometheus::register_int_counter_with_registry; -use tracing::{instrument, Span}; +use tracing::{Span, instrument}; use super::{ - get_metric_opts, get_metrics_registry, GetHyperlightMetric, HyperlightMetric, - HyperlightMetricOps, + GetHyperlightMetric, HyperlightMetric, HyperlightMetricOps, get_metric_opts, + get_metrics_registry, }; -use crate::{new_error, HyperlightError, Result}; +use crate::{HyperlightError, Result, new_error}; /// A named counter backed by an `AtomicU64` #[derive(Debug)] diff --git a/src/hyperlight_host/src/metrics/int_counter_vec.rs b/src/hyperlight_host/src/metrics/int_counter_vec.rs index 84ed14050..7513f0a01 100644 --- a/src/hyperlight_host/src/metrics/int_counter_vec.rs +++ b/src/hyperlight_host/src/metrics/int_counter_vec.rs @@ -16,13 +16,13 @@ limitations under the License. use prometheus::core::{AtomicU64, GenericCounterVec}; use prometheus::register_int_counter_vec_with_registry; -use tracing::{instrument, Span}; +use tracing::{Span, instrument}; use super::{ - get_metric_opts, get_metrics_registry, GetHyperlightMetric, HyperlightMetric, - HyperlightMetricOps, + GetHyperlightMetric, HyperlightMetric, HyperlightMetricOps, get_metric_opts, + get_metrics_registry, }; -use crate::{new_error, HyperlightError, Result}; +use crate::{HyperlightError, Result, new_error}; /// A 64-bit counter #[derive(Debug)] diff --git a/src/hyperlight_host/src/metrics/int_gauge.rs b/src/hyperlight_host/src/metrics/int_gauge.rs index ed595d462..e6ba05b51 100644 --- a/src/hyperlight_host/src/metrics/int_gauge.rs +++ b/src/hyperlight_host/src/metrics/int_gauge.rs @@ -16,13 +16,13 @@ limitations under the License. use prometheus::core::{AtomicI64, GenericGauge}; use prometheus::register_int_gauge_with_registry; -use tracing::{instrument, Span}; +use tracing::{Span, instrument}; use super::{ - get_metric_opts, get_metrics_registry, GetHyperlightMetric, HyperlightMetric, - HyperlightMetricOps, + GetHyperlightMetric, HyperlightMetric, HyperlightMetricOps, get_metric_opts, + get_metrics_registry, }; -use crate::{new_error, HyperlightError, Result}; +use crate::{HyperlightError, Result, new_error}; /// A gauge backed by an `AtomicI64` #[derive(Debug)] diff --git a/src/hyperlight_host/src/metrics/int_gauge_vec.rs b/src/hyperlight_host/src/metrics/int_gauge_vec.rs index de96f2b25..68036e87f 100644 --- a/src/hyperlight_host/src/metrics/int_gauge_vec.rs +++ b/src/hyperlight_host/src/metrics/int_gauge_vec.rs @@ -16,13 +16,13 @@ limitations under the License. use prometheus::core::{AtomicI64, GenericGaugeVec}; use prometheus::register_int_gauge_vec_with_registry; -use tracing::{instrument, Span}; +use tracing::{Span, instrument}; use super::{ - get_metric_opts, get_metrics_registry, GetHyperlightMetric, HyperlightMetric, - HyperlightMetricOps, + GetHyperlightMetric, HyperlightMetric, HyperlightMetricOps, get_metric_opts, + get_metrics_registry, }; -use crate::{new_error, HyperlightError, Result}; +use crate::{HyperlightError, Result, new_error}; /// A list of gauges, each backed by an `AtomicI64` #[derive(Debug)] diff --git a/src/hyperlight_host/src/metrics/mod.rs b/src/hyperlight_host/src/metrics/mod.rs index 7ff3e6faf..0a38fc277 100644 --- a/src/hyperlight_host/src/metrics/mod.rs +++ b/src/hyperlight_host/src/metrics/mod.rs @@ -19,11 +19,11 @@ use std::sync::Once; use log::error; use once_cell::sync::OnceCell; -use prometheus::{default_registry, histogram_opts, opts, HistogramOpts, Opts, Registry}; +use prometheus::{HistogramOpts, Opts, Registry, default_registry, histogram_opts, opts}; use strum::{IntoEnumIterator, VariantNames}; use crate::error::HyperlightError::{Error, MetricNotFound}; -use crate::{log_then_return, new_error, Result}; +use crate::{Result, log_then_return, new_error}; mod int_gauge_vec; /// An Integer Gauge Metric for Hyperlight /// diff --git a/src/hyperlight_host/src/sandbox/config.rs b/src/hyperlight_host/src/sandbox/config.rs index e0bbaddbe..e4166a6d7 100644 --- a/src/hyperlight_host/src/sandbox/config.rs +++ b/src/hyperlight_host/src/sandbox/config.rs @@ -17,7 +17,7 @@ limitations under the License. use std::cmp::{max, min}; use std::time::Duration; -use tracing::{instrument, Span}; +use tracing::{Span, instrument}; use crate::mem::exe::ExeInfo; diff --git a/src/hyperlight_host/src/sandbox/host_funcs.rs b/src/hyperlight_host/src/sandbox/host_funcs.rs index 15ef9a46f..5f6052f37 100644 --- a/src/hyperlight_host/src/sandbox/host_funcs.rs +++ b/src/hyperlight_host/src/sandbox/host_funcs.rs @@ -20,14 +20,14 @@ use hyperlight_common::flatbuffer_wrappers::function_types::{ParameterValue, Ret use hyperlight_common::flatbuffer_wrappers::host_function_definition::HostFunctionDefinition; use hyperlight_common::flatbuffer_wrappers::host_function_details::HostFunctionDetails; use termcolor::{Color, ColorChoice, ColorSpec, StandardStream, WriteColor}; -use tracing::{instrument, Span}; +use tracing::{Span, instrument}; use super::{ExtraAllowedSyscall, FunctionsMap}; +use crate::HyperlightError::HostFunctionNotFound; use crate::func::HyperlightFunction; use crate::mem::mgr::SandboxMemoryManager; use crate::mem::shared_mem::ExclusiveSharedMemory; -use crate::HyperlightError::HostFunctionNotFound; -use crate::{new_error, Result}; +use crate::{Result, new_error}; #[derive(Default, Clone)] /// A Wrapper around details of functions exposed by the Host diff --git a/src/hyperlight_host/src/sandbox/initialized_multi_use.rs b/src/hyperlight_host/src/sandbox/initialized_multi_use.rs index 43f3c7211..7d630efdc 100644 --- a/src/hyperlight_host/src/sandbox/initialized_multi_use.rs +++ b/src/hyperlight_host/src/sandbox/initialized_multi_use.rs @@ -19,17 +19,17 @@ use std::sync::{Arc, Mutex}; use hyperlight_common::flatbuffer_wrappers::function_types::{ ParameterValue, ReturnType, ReturnValue, }; -use tracing::{instrument, Span}; +use tracing::{Span, instrument}; use super::host_funcs::HostFuncsWrapper; use super::{MemMgrWrapper, WrapperGetter}; +use crate::Result; use crate::func::call_ctx::MultiUseGuestCallContext; use crate::func::guest_dispatch::call_function_on_guest; use crate::hypervisor::hypervisor_handler::HypervisorHandler; use crate::mem::shared_mem::HostSharedMemory; use crate::sandbox_state::sandbox::{DevolvableSandbox, EvolvableSandbox, Sandbox}; use crate::sandbox_state::transition::{MultiUseContextCallback, Noop}; -use crate::Result; /// A sandbox that supports being used Multiple times. /// The implication of being used multiple times is two-fold: @@ -59,7 +59,10 @@ impl Drop for MultiUseSandbox { match self.hv_handler.kill_hypervisor_handler_thread() { Ok(_) => {} Err(e) => { - log::error!("[POTENTIAL THREAD LEAK] Potentially failed to kill hypervisor handler thread when dropping MultiUseSandbox: {:?}", e); + log::error!( + "[POTENTIAL THREAD LEAK] Potentially failed to kill hypervisor handler thread when dropping MultiUseSandbox: {:?}", + e + ); } } } diff --git a/src/hyperlight_host/src/sandbox/leaked_outb.rs b/src/hyperlight_host/src/sandbox/leaked_outb.rs index 87fc6c344..e3747ad5b 100644 --- a/src/hyperlight_host/src/sandbox/leaked_outb.rs +++ b/src/hyperlight_host/src/sandbox/leaked_outb.rs @@ -17,7 +17,7 @@ limitations under the License. use std::os::raw::c_void; use std::sync::{Arc, Mutex}; -use tracing::{instrument, Span}; +use tracing::{Span, instrument}; use crate::hypervisor::handlers::{OutBHandlerCaller, OutBHandlerWrapper}; use crate::mem::custom_drop::CustomPtrDrop; @@ -79,7 +79,7 @@ pub(crate) struct LeakedOutBWrapper<'a> { hdl_ptr: Arc>>, } -impl<'a> LeakedOutBWrapper<'a> { +impl LeakedOutBWrapper<'_> { #[instrument(skip_all, parent = Span::current(), level = "Trace")] pub(crate) fn new( mgr: &mut SandboxMemoryManager, diff --git a/src/hyperlight_host/src/sandbox/mem_access.rs b/src/hyperlight_host/src/sandbox/mem_access.rs index 7bf4fbdc2..9f1e238a7 100644 --- a/src/hyperlight_host/src/sandbox/mem_access.rs +++ b/src/hyperlight_host/src/sandbox/mem_access.rs @@ -16,7 +16,7 @@ limitations under the License. use std::sync::{Arc, Mutex}; -use tracing::{instrument, Span}; +use tracing::{Span, instrument}; use super::mem_mgr::MemMgrWrapper; use crate::error::HyperlightError::StackOverflow; @@ -26,7 +26,7 @@ use crate::hypervisor::handlers::{ MemAccessHandler, MemAccessHandlerFunction, MemAccessHandlerWrapper, }; use crate::mem::shared_mem::HostSharedMemory; -use crate::{log_then_return, Result}; +use crate::{Result, log_then_return}; #[instrument(err(Debug), skip_all, parent = Span::current(), level= "Trace")] pub(super) fn handle_mem_access_impl(wrapper: &MemMgrWrapper) -> Result<()> { diff --git a/src/hyperlight_host/src/sandbox/mem_mgr.rs b/src/hyperlight_host/src/sandbox/mem_mgr.rs index 8099b0991..89ca36775 100644 --- a/src/hyperlight_host/src/sandbox/mem_mgr.rs +++ b/src/hyperlight_host/src/sandbox/mem_mgr.rs @@ -14,14 +14,14 @@ See the License for the specific language governing permissions and limitations under the License. */ -use tracing::{instrument, Span}; +use tracing::{Span, instrument}; +use crate::Result; use crate::mem::layout::SandboxMemoryLayout; -use crate::mem::mgr::{SandboxMemoryManager, STACK_COOKIE_LEN}; +use crate::mem::mgr::{STACK_COOKIE_LEN, SandboxMemoryManager}; use crate::mem::shared_mem::{ ExclusiveSharedMemory, GuestSharedMemory, HostSharedMemory, SharedMemory, }; -use crate::Result; /// StackCookie pub type StackCookie = [u8; STACK_COOKIE_LEN]; diff --git a/src/hyperlight_host/src/sandbox/metrics.rs b/src/hyperlight_host/src/sandbox/metrics.rs index 05ef9bae1..3c40b60db 100644 --- a/src/hyperlight_host/src/sandbox/metrics.rs +++ b/src/hyperlight_host/src/sandbox/metrics.rs @@ -22,7 +22,7 @@ use std::sync::Once; use once_cell::sync::OnceCell; use strum::{EnumIter, IntoStaticStr, VariantNames}; -use tracing::{instrument, Span}; +use tracing::{Span, instrument}; use crate::metrics::{ HyperlightMetric, HyperlightMetricDefinition, HyperlightMetricEnum, HyperlightMetricType, diff --git a/src/hyperlight_host/src/sandbox/mod.rs b/src/hyperlight_host/src/sandbox/mod.rs index a88556878..ab81002ae 100644 --- a/src/hyperlight_host/src/sandbox/mod.rs +++ b/src/hyperlight_host/src/sandbox/mod.rs @@ -56,7 +56,7 @@ pub use config::SandboxConfiguration; pub use initialized_multi_use::MultiUseSandbox; /// Re-export for `SandboxRunOptions` type pub use run_options::SandboxRunOptions; -use tracing::{instrument, Span}; +use tracing::{Span, instrument}; /// Re-export for `GuestBinary` type pub use uninitialized::GuestBinary; /// Re-export for `UninitializedSandbox` type @@ -161,7 +161,7 @@ mod tests { use crate::sandbox::uninitialized::GuestBinary; use crate::sandbox_state::sandbox::EvolvableSandbox; use crate::sandbox_state::transition::Noop; - use crate::{new_error, MultiUseSandbox, UninitializedSandbox}; + use crate::{MultiUseSandbox, UninitializedSandbox, new_error}; #[test] // TODO: add support for testing on WHP diff --git a/src/hyperlight_host/src/sandbox/outb.rs b/src/hyperlight_host/src/sandbox/outb.rs index dd359ebb2..ec959964a 100644 --- a/src/hyperlight_host/src/sandbox/outb.rs +++ b/src/hyperlight_host/src/sandbox/outb.rs @@ -20,7 +20,7 @@ use hyperlight_common::flatbuffer_wrappers::function_types::ParameterValue; use hyperlight_common::flatbuffer_wrappers::guest_error::ErrorCode; use hyperlight_common::flatbuffer_wrappers::guest_log_data::GuestLogData; use log::{Level, Record}; -use tracing::{instrument, Span}; +use tracing::{Span, instrument}; use tracing_log::format_trace; use super::host_funcs::HostFuncsWrapper; @@ -28,7 +28,7 @@ use super::mem_mgr::MemMgrWrapper; use crate::hypervisor::handlers::{OutBHandler, OutBHandlerFunction, OutBHandlerWrapper}; use crate::mem::mgr::SandboxMemoryManager; use crate::mem::shared_mem::HostSharedMemory; -use crate::{new_error, HyperlightError, Result}; +use crate::{HyperlightError, Result, new_error}; pub(super) enum OutBAction { Log, @@ -180,7 +180,7 @@ pub(crate) fn outb_handler_wrapper( #[cfg(test)] mod tests { use hyperlight_common::flatbuffer_wrappers::guest_log_level::LogLevel; - use hyperlight_testing::logger::{Logger, LOGGER}; + use hyperlight_testing::logger::{LOGGER, Logger}; use log::Level; use tracing_core::callsite::rebuild_interest_cache; @@ -188,8 +188,8 @@ mod tests { use crate::mem::layout::SandboxMemoryLayout; use crate::mem::mgr::SandboxMemoryManager; use crate::mem::shared_mem::SharedMemory; - use crate::sandbox::outb::GuestLogData; use crate::sandbox::SandboxConfiguration; + use crate::sandbox::outb::GuestLogData; use crate::testing::log_values::test_value_as_str; use crate::testing::simple_guest_exe_info; diff --git a/src/hyperlight_host/src/sandbox/run_options.rs b/src/hyperlight_host/src/sandbox/run_options.rs index 6c5f6904b..1d0c77bca 100644 --- a/src/hyperlight_host/src/sandbox/run_options.rs +++ b/src/hyperlight_host/src/sandbox/run_options.rs @@ -14,7 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ -use tracing::{instrument, Span}; +use tracing::{Span, instrument}; /// Configuration options for setting up a new `UninitializedSandbox` and /// subsequent initialized sandboxes, including `MultiUseSandbox`. diff --git a/src/hyperlight_host/src/sandbox/uninitialized.rs b/src/hyperlight_host/src/sandbox/uninitialized.rs index e38647d8a..6beaade4e 100644 --- a/src/hyperlight_host/src/sandbox/uninitialized.rs +++ b/src/hyperlight_host/src/sandbox/uninitialized.rs @@ -20,23 +20,23 @@ use std::path::Path; use std::sync::{Arc, Mutex}; use std::time::Duration; -use tracing::{instrument, Span}; +use tracing::{Span, instrument}; #[cfg(gdb)] use super::config::DebugInfo; -use super::host_funcs::{default_writer_func, HostFuncsWrapper}; +use super::host_funcs::{HostFuncsWrapper, default_writer_func}; use super::mem_mgr::MemMgrWrapper; use super::run_options::SandboxRunOptions; use super::uninitialized_evolve::evolve_impl_multi_use; use crate::error::HyperlightError::GuestBinaryShouldBeAFile; use crate::func::host_functions::HostFunction1; use crate::mem::exe::ExeInfo; -use crate::mem::mgr::{SandboxMemoryManager, STACK_COOKIE_LEN}; +use crate::mem::mgr::{STACK_COOKIE_LEN, SandboxMemoryManager}; use crate::mem::shared_mem::ExclusiveSharedMemory; use crate::sandbox::SandboxConfiguration; use crate::sandbox_state::sandbox::EvolvableSandbox; use crate::sandbox_state::transition::Noop; -use crate::{log_build_details, log_then_return, new_error, MultiUseSandbox, Result}; +use crate::{MultiUseSandbox, Result, log_build_details, log_then_return, new_error}; /// A preliminary `Sandbox`, not yet ready to execute guest code. /// @@ -304,7 +304,7 @@ impl UninitializedSandbox { // Hyperlight is only supported on Windows 11 and Windows Server 2022 and later #[cfg(target_os = "windows")] fn check_windows_version() -> Result<()> { - use windows_version::{is_server, OsVersion}; + use windows_version::{OsVersion, is_server}; const WINDOWS_MAJOR: u32 = 10; const WINDOWS_MINOR: u32 = 0; const WINDOWS_PACK: u32 = 0; @@ -334,24 +334,24 @@ mod tests { use crossbeam_queue::ArrayQueue; use hyperlight_common::flatbuffer_wrappers::function_types::{ParameterValue, ReturnValue}; - use hyperlight_testing::logger::{Logger as TestLogger, LOGGER as TEST_LOGGER}; + use hyperlight_testing::logger::{LOGGER as TEST_LOGGER, Logger as TestLogger}; use hyperlight_testing::tracing_subscriber::TracingSubscriber as TestSubcriber; use hyperlight_testing::{simple_guest_as_string, simple_guest_exe_as_string}; use log::Level; use serde_json::{Map, Value}; use serial_test::serial; use tracing::Level as tracing_level; - use tracing_core::callsite::rebuild_interest_cache; use tracing_core::Subscriber; + use tracing_core::callsite::rebuild_interest_cache; use uuid::Uuid; use crate::func::{HostFunction1, HostFunction2}; - use crate::sandbox::uninitialized::GuestBinary; use crate::sandbox::SandboxConfiguration; + use crate::sandbox::uninitialized::GuestBinary; use crate::sandbox_state::sandbox::EvolvableSandbox; use crate::sandbox_state::transition::Noop; use crate::testing::log_values::{test_value_as_str, try_to_strings}; - use crate::{new_error, MultiUseSandbox, Result, SandboxRunOptions, UninitializedSandbox}; + use crate::{MultiUseSandbox, Result, SandboxRunOptions, UninitializedSandbox, new_error}; #[test] fn test_in_process() { @@ -1062,9 +1062,11 @@ mod tests { let logcall = TEST_LOGGER.get_log_call(16).unwrap(); assert_eq!(Level::Error, logcall.level); - assert!(logcall - .args - .starts_with("error=Error(\"GuestBinary not found:")); + assert!( + logcall + .args + .starts_with("error=Error(\"GuestBinary not found:") + ); assert_eq!("hyperlight_host::sandbox::uninitialized", logcall.target); // Log record 18 @@ -1116,9 +1118,11 @@ mod tests { let logcall = TEST_LOGGER.get_log_call(1).unwrap(); assert_eq!(Level::Error, logcall.level); - assert!(logcall - .args - .starts_with("error=Error(\"GuestBinary not found:")); + assert!( + logcall + .args + .starts_with("error=Error(\"GuestBinary not found:") + ); assert_eq!("hyperlight_host::sandbox::uninitialized", logcall.target); } { diff --git a/src/hyperlight_host/src/sandbox/uninitialized_evolve.rs b/src/hyperlight_host/src/sandbox/uninitialized_evolve.rs index f9e99d7aa..ba04983e4 100644 --- a/src/hyperlight_host/src/sandbox/uninitialized_evolve.rs +++ b/src/hyperlight_host/src/sandbox/uninitialized_evolve.rs @@ -18,7 +18,7 @@ use core::time::Duration; use std::sync::{Arc, Mutex}; use rand::Rng; -use tracing::{instrument, Span}; +use tracing::{Span, instrument}; #[cfg(gdb)] use super::mem_access::dbg_mem_access_handler_wrapper; @@ -35,7 +35,7 @@ use crate::sandbox::mem_access::mem_access_handler_wrapper; use crate::sandbox::outb::outb_handler_wrapper; use crate::sandbox::{HostSharedMemory, MemMgrWrapper}; use crate::sandbox_state::sandbox::Sandbox; -use crate::{new_error, MultiUseSandbox, Result, UninitializedSandbox}; +use crate::{MultiUseSandbox, Result, UninitializedSandbox, new_error}; /// The implementation for evolving `UninitializedSandbox`es to /// `Sandbox`es. @@ -159,8 +159,8 @@ mod tests { use hyperlight_testing::{callback_guest_as_string, simple_guest_as_string}; use super::evolve_impl_multi_use; - use crate::sandbox::uninitialized::GuestBinary; use crate::UninitializedSandbox; + use crate::sandbox::uninitialized::GuestBinary; #[test] fn test_evolve() { diff --git a/src/hyperlight_host/src/sandbox_state/sandbox.rs b/src/hyperlight_host/src/sandbox_state/sandbox.rs index 2ddde372b..403d006c9 100644 --- a/src/hyperlight_host/src/sandbox_state/sandbox.rs +++ b/src/hyperlight_host/src/sandbox_state/sandbox.rs @@ -17,7 +17,7 @@ limitations under the License. use std::fmt::Debug; use std::panic; -use tracing::{instrument, Span}; +use tracing::{Span, instrument}; use super::transition::TransitionMetadata; use crate::Result; diff --git a/src/hyperlight_host/src/sandbox_state/transition.rs b/src/hyperlight_host/src/sandbox_state/transition.rs index 6583952d9..42a0eaf0a 100644 --- a/src/hyperlight_host/src/sandbox_state/transition.rs +++ b/src/hyperlight_host/src/sandbox_state/transition.rs @@ -16,11 +16,11 @@ limitations under the License. use std::marker::PhantomData; -use tracing::{instrument, Span}; +use tracing::{Span, instrument}; use super::sandbox::Sandbox; -use crate::func::call_ctx::MultiUseGuestCallContext; use crate::Result; +use crate::func::call_ctx::MultiUseGuestCallContext; /// Metadata about an evolution or devolution. Any `Sandbox` implementation /// that also implements `EvolvableSandbox` or `DevolvableSandbox` @@ -100,7 +100,6 @@ impl TransitionMetadata for Noop where F: FnOnce(&mut MultiUseGuestCallContext) -> Result<()> + 'func, @@ -110,14 +109,14 @@ where cb: F, } -impl<'a, Cur: Sandbox, Next: Sandbox, F> TransitionMetadata - for MultiUseContextCallback<'a, Cur, F> +impl TransitionMetadata + for MultiUseContextCallback<'_, Cur, F> where F: FnOnce(&mut MultiUseGuestCallContext) -> Result<()>, { } -impl<'a, Cur: Sandbox, F> MultiUseContextCallback<'a, Cur, F> +impl MultiUseContextCallback<'_, Cur, F> where F: FnOnce(&mut MultiUseGuestCallContext) -> Result<()>, { @@ -143,8 +142,8 @@ where #[cfg(test)] mod tests { use super::Noop; - use crate::sandbox_state::sandbox::{DevolvableSandbox, EvolvableSandbox, Sandbox}; use crate::Result; + use crate::sandbox_state::sandbox::{DevolvableSandbox, EvolvableSandbox, Sandbox}; #[derive(Debug, Eq, PartialEq, Clone)] struct MySandbox1 {} diff --git a/src/hyperlight_host/src/seccomp/guest.rs b/src/hyperlight_host/src/seccomp/guest.rs index 97aadccfa..824e61782 100644 --- a/src/hyperlight_host/src/seccomp/guest.rs +++ b/src/hyperlight_host/src/seccomp/guest.rs @@ -21,7 +21,7 @@ use seccompiler::{ }; use crate::sandbox::ExtraAllowedSyscall; -use crate::{and, or, Result}; +use crate::{Result, and, or}; fn syscalls_allowlist() -> Result)>> { Ok(vec![ diff --git a/src/hyperlight_host/src/testing/log_values.rs b/src/hyperlight_host/src/testing/log_values.rs index 9017d394e..4b3fb561e 100644 --- a/src/hyperlight_host/src/testing/log_values.rs +++ b/src/hyperlight_host/src/testing/log_values.rs @@ -16,7 +16,7 @@ limitations under the License. use serde_json::{Map, Value}; -use crate::{new_error, Result}; +use crate::{Result, new_error}; /// Call `check_value_as_str` and panic if it returned an `Err`. Otherwise, /// do nothing. diff --git a/src/hyperlight_host/src/testing/mod.rs b/src/hyperlight_host/src/testing/mod.rs index 4cbc5ca83..b2399daca 100644 --- a/src/hyperlight_host/src/testing/mod.rs +++ b/src/hyperlight_host/src/testing/mod.rs @@ -20,7 +20,7 @@ use std::path::PathBuf; use hyperlight_testing::rust_guest_as_pathbuf; use crate::mem::exe::ExeInfo; -use crate::{new_error, Result}; +use crate::{Result, new_error}; pub(crate) mod log_values; /// Get an `ExeInfo` representing `simpleguest.exe` diff --git a/src/hyperlight_host/tests/integration_test.rs b/src/hyperlight_host/tests/integration_test.rs index eb3ad8228..40098c340 100644 --- a/src/hyperlight_host/tests/integration_test.rs +++ b/src/hyperlight_host/tests/integration_test.rs @@ -471,7 +471,7 @@ fn recursive_stack_allocate_overflow() { #[test] #[ignore] fn log_message() { - use hyperlight_testing::simplelogger::{SimpleLogger, LOGGER}; + use hyperlight_testing::simplelogger::{LOGGER, SimpleLogger}; // init SimpleLogger::initialize_test_logger(); diff --git a/src/hyperlight_host/tests/sandbox_host_tests.rs b/src/hyperlight_host/tests/sandbox_host_tests.rs index cb8452cac..47f12e4ce 100644 --- a/src/hyperlight_host/tests/sandbox_host_tests.rs +++ b/src/hyperlight_host/tests/sandbox_host_tests.rs @@ -23,7 +23,7 @@ use hyperlight_host::sandbox::SandboxConfiguration; use hyperlight_host::sandbox_state::sandbox::EvolvableSandbox; use hyperlight_host::sandbox_state::transition::Noop; use hyperlight_host::{ - new_error, GuestBinary, HyperlightError, MultiUseSandbox, Result, UninitializedSandbox, + GuestBinary, HyperlightError, MultiUseSandbox, Result, UninitializedSandbox, new_error, }; use hyperlight_testing::simple_guest_as_string; #[cfg(target_os = "windows")] @@ -317,7 +317,7 @@ fn multiple_parameters() { "Message: arg1:{} arg2:{} arg3:{} arg4:{} arg5:{} arg6:{} arg7:{} arg8:{} arg9:{} arg10:{} arg11:{}.", "1", 2, 3, "4", "5", true, false, 8, 9, 10, 3.123 ), - ) + ), ]; for mut sandbox in get_simpleguest_sandboxes(Some(&writer_func)).into_iter() { @@ -482,11 +482,13 @@ fn simple_test_helper() -> Result<()> { expected_calls ); - assert!(messages - .try_lock() - .map_err(|e| new_error!("Error locking at {}:{}: {}", file!(), line!(), e))? - .iter() - .all(|msg| msg == message)); + assert!( + messages + .try_lock() + .map_err(|e| new_error!("Error locking at {}:{}: {}", file!(), line!(), e))? + .iter() + .all(|msg| msg == message) + ); Ok(()) } diff --git a/src/hyperlight_testing/Cargo.toml b/src/hyperlight_testing/Cargo.toml index cee179de4..308320118 100644 --- a/src/hyperlight_testing/Cargo.toml +++ b/src/hyperlight_testing/Cargo.toml @@ -1,6 +1,11 @@ [package] name = "hyperlight-testing" -edition = "2021" +version.workspace = true +edition.workspace = true +rust-version.workspace = true + +[lints] +workspace = true [dependencies] anyhow = "1.0.97" diff --git a/src/hyperlight_testing/src/lib.rs b/src/hyperlight_testing/src/lib.rs index 479e59e8b..c2888d1e5 100644 --- a/src/hyperlight_testing/src/lib.rs +++ b/src/hyperlight_testing/src/lib.rs @@ -19,7 +19,7 @@ limitations under the License. use std::env; use std::path::PathBuf; -use anyhow::{anyhow, Result}; +use anyhow::{Result, anyhow}; pub const MANIFEST_DIR: &str = env!("CARGO_MANIFEST_DIR"); pub mod logger; diff --git a/src/hyperlight_testing/src/logger.rs b/src/hyperlight_testing/src/logger.rs index 136558b0d..1313496ac 100644 --- a/src/hyperlight_testing/src/logger.rs +++ b/src/hyperlight_testing/src/logger.rs @@ -18,7 +18,7 @@ use std::cell::RefCell; use std::sync::Once; use std::thread::current; -use log::{set_logger, set_max_level, Level, LevelFilter, Log, Metadata, Record}; +use log::{Level, LevelFilter, Log, Metadata, Record, set_logger, set_max_level}; use once_cell::sync::Lazy; use tracing_log::LogTracer; diff --git a/src/hyperlight_testing/src/simplelogger.rs b/src/hyperlight_testing/src/simplelogger.rs index 0abdf89bd..f4bc17164 100644 --- a/src/hyperlight_testing/src/simplelogger.rs +++ b/src/hyperlight_testing/src/simplelogger.rs @@ -18,10 +18,10 @@ limitations under the License. // it will only log messages from the hyperlight-guest target. It will not log messages from other targets. // this target is only used when handling an outb log request from the guest, so this logger will only capture those messages. -use std::sync::Once; +use std::sync::{Mutex, Once}; use std::thread::current; -use log::{set_logger, set_max_level, Level, Log, Metadata, Record}; +use log::{Level, Log, Metadata, Record, set_logger, set_max_level}; pub static LOGGER: SimpleLogger = SimpleLogger {}; static INITLOGGER: Once = Once::new(); @@ -35,8 +35,8 @@ pub struct LogCall { pub module_path: Option, } -static mut LOGCALLS: Vec = Vec::::new(); -static mut NUMBER_OF_ENABLED_CALLS: usize = 0; +static LOGCALLS: Mutex> = Mutex::new(Vec::::new()); +static NUMBER_OF_ENABLED_CALLS: Mutex = Mutex::new(0); pub struct SimpleLogger {} @@ -49,29 +49,23 @@ impl SimpleLogger { } pub fn num_enabled_calls(&self) -> usize { - unsafe { NUMBER_OF_ENABLED_CALLS } + *NUMBER_OF_ENABLED_CALLS.lock().unwrap() } pub fn num_log_calls(&self) -> usize { - unsafe { LOGCALLS.len() } + LOGCALLS.lock().unwrap().len() } pub fn get_log_call(&self, idx: usize) -> Option { - unsafe { LOGCALLS.get(idx).cloned() } + LOGCALLS.lock().unwrap().get(idx).cloned() } pub fn clear_log_calls(&self) { - unsafe { - LOGCALLS.clear(); - NUMBER_OF_ENABLED_CALLS = 0; - } + LOGCALLS.lock().unwrap().clear(); + *NUMBER_OF_ENABLED_CALLS.lock().unwrap() = 0; } pub fn test_log_records)>(&self, f: F) { - unsafe { - // this logger is only used for testing so unsafe is fine here - #[allow(static_mut_refs)] - f(&LOGCALLS); - }; + f(&LOGCALLS.lock().unwrap()); self.clear_log_calls(); } } @@ -82,36 +76,32 @@ impl Log for SimpleLogger { // because the guest derives its log level from the host log level then the number times that enabled is called for // the "hyperlight-guest" target will be the same as the number of messages logged by the guest. // In other words this function should always return true for the "hyperlight-guest" target. - unsafe { - if metadata.target() == "hyperlight-guest" { - NUMBER_OF_ENABLED_CALLS += 1; - } - metadata.target() == "hyperlight-guest" && metadata.level() <= log::max_level() + if metadata.target() == "hyperlight-guest" { + *NUMBER_OF_ENABLED_CALLS.lock().unwrap() += 1; } + metadata.target() == "hyperlight-guest" && metadata.level() <= log::max_level() } fn log(&self, record: &Record) { if !self.enabled(record.metadata()) { return; } - unsafe { - LOGCALLS.push(LogCall { - level: record.level(), - args: format!("{}", record.args()), - target: record.target().to_string(), - line: record.line(), - file: match record.file() { - None => record.file_static().map(|file| file.to_string()), - Some(file) => Some(file.to_string()), - }, - module_path: match record.module_path() { - None => record - .module_path_static() - .map(|module_path| module_path.to_string()), - Some(module_path) => Some(module_path.to_string()), - }, - }); - }; + LOGCALLS.lock().unwrap().push(LogCall { + level: record.level(), + args: format!("{}", record.args()), + target: record.target().to_string(), + line: record.line(), + file: match record.file() { + None => record.file_static().map(|file| file.to_string()), + Some(file) => Some(file.to_string()), + }, + module_path: match record.module_path() { + None => record + .module_path_static() + .map(|module_path| module_path.to_string()), + Some(module_path) => Some(module_path.to_string()), + }, + }); println!("Thread {:?} {:?}", current().id(), record); } diff --git a/src/hyperlight_testing/src/tracing_subscriber.rs b/src/hyperlight_testing/src/tracing_subscriber.rs index 32f34c5b7..211d32743 100644 --- a/src/hyperlight_testing/src/tracing_subscriber.rs +++ b/src/hyperlight_testing/src/tracing_subscriber.rs @@ -17,7 +17,7 @@ limitations under the License. use std::cell::RefCell; use std::collections::HashMap; -use serde_json::{json, to_string_pretty, Value}; +use serde_json::{Value, json, to_string_pretty}; use tracing::Subscriber; use tracing_core::event::Event; use tracing_core::metadata::Metadata; diff --git a/src/tests/rust_guests/callbackguest/Cargo.lock b/src/tests/rust_guests/callbackguest/Cargo.lock index a0a2626e5..1795c5eb4 100644 --- a/src/tests/rust_guests/callbackguest/Cargo.lock +++ b/src/tests/rust_guests/callbackguest/Cargo.lock @@ -1,12 +1,12 @@ # This file is automatically @generated by Cargo. # It is not intended for manual editing. -version = 3 +version = 4 [[package]] name = "anyhow" -version = "1.0.96" +version = "1.0.97" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6b964d184e89d9b6b67dd2715bc8e74cf3107fb2b529990c90cf517326150bf4" +checksum = "dcfed56ad506cb2c684a14971b8861fdc3baaaae314b9e5f9bb532cbe3ba7a4f" [[package]] name = "autocfg" diff --git a/src/tests/rust_guests/callbackguest/Cargo.toml b/src/tests/rust_guests/callbackguest/Cargo.toml index 0f9c01028..a1f8c7556 100644 --- a/src/tests/rust_guests/callbackguest/Cargo.toml +++ b/src/tests/rust_guests/callbackguest/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "callbackguest" version = "0.1.0" -edition = "2021" +edition = "2024" [dependencies] hyperlight-guest = { path = "../../../hyperlight_guest" } diff --git a/src/tests/rust_guests/callbackguest/src/main.rs b/src/tests/rust_guests/callbackguest/src/main.rs index c787599d5..df9f6d501 100644 --- a/src/tests/rust_guests/callbackguest/src/main.rs +++ b/src/tests/rust_guests/callbackguest/src/main.rs @@ -161,7 +161,7 @@ fn call_host_spin(_: &FunctionCall) -> Result> { Ok(get_flatbuffer_result(())) } -#[no_mangle] +#[unsafe(no_mangle)] pub extern "C" fn hyperlight_main() { let print_output_def = GuestFunctionDefinition::new( "PrintOutput".to_string(), @@ -240,7 +240,7 @@ pub extern "C" fn hyperlight_main() { register_function(call_host_spin_def); } -#[no_mangle] +#[unsafe(no_mangle)] pub fn guest_dispatch_function(function_call: FunctionCall) -> Result> { Err(HyperlightGuestError::new( ErrorCode::GuestFunctionNotFound, diff --git a/src/tests/rust_guests/dummyguest/Cargo.toml b/src/tests/rust_guests/dummyguest/Cargo.toml index 619031cae..a0a95864f 100644 --- a/src/tests/rust_guests/dummyguest/Cargo.toml +++ b/src/tests/rust_guests/dummyguest/Cargo.toml @@ -1,4 +1,4 @@ [package] name = "dummyguest" version = "0.4.0" -edition = "2021" \ No newline at end of file +edition = "2024" \ No newline at end of file diff --git a/src/tests/rust_guests/dummyguest/src/main.rs b/src/tests/rust_guests/dummyguest/src/main.rs index fd15f81b1..569860640 100644 --- a/src/tests/rust_guests/dummyguest/src/main.rs +++ b/src/tests/rust_guests/dummyguest/src/main.rs @@ -42,7 +42,7 @@ fn mmio_read() { } #[allow(non_snake_case)] -#[no_mangle] +#[unsafe(no_mangle)] pub extern "win64" fn entrypoint(a: i64, b: i64, c: i32) -> i32 { if a != 0x230000 || b != 1234567890 || c != 4096 { mmio_read(); diff --git a/src/tests/rust_guests/simpleguest/Cargo.lock b/src/tests/rust_guests/simpleguest/Cargo.lock index a0978ff71..94836759d 100644 --- a/src/tests/rust_guests/simpleguest/Cargo.lock +++ b/src/tests/rust_guests/simpleguest/Cargo.lock @@ -1,12 +1,12 @@ # This file is automatically @generated by Cargo. # It is not intended for manual editing. -version = 3 +version = 4 [[package]] name = "anyhow" -version = "1.0.96" +version = "1.0.97" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6b964d184e89d9b6b67dd2715bc8e74cf3107fb2b529990c90cf517326150bf4" +checksum = "dcfed56ad506cb2c684a14971b8861fdc3baaaae314b9e5f9bb532cbe3ba7a4f" [[package]] name = "autocfg" @@ -215,6 +215,7 @@ dependencies = [ "hyperlight-common", "hyperlight-guest", "log", + "spin", ] [[package]] diff --git a/src/tests/rust_guests/simpleguest/Cargo.toml b/src/tests/rust_guests/simpleguest/Cargo.toml index f414efe86..15148d0d4 100644 --- a/src/tests/rust_guests/simpleguest/Cargo.toml +++ b/src/tests/rust_guests/simpleguest/Cargo.toml @@ -1,9 +1,10 @@ [package] name = "simpleguest" version = "0.4.0" -edition = "2021" +edition = "2024" [dependencies] hyperlight-guest = { path = "../../../hyperlight_guest" } hyperlight-common = { path = "../../../hyperlight_common", default-features = false } log = {version = "0.4", default-features = false } +spin = "0.9.8" diff --git a/src/tests/rust_guests/simpleguest/src/main.rs b/src/tests/rust_guests/simpleguest/src/main.rs index 45dd558c7..a9a1421a8 100644 --- a/src/tests/rust_guests/simpleguest/src/main.rs +++ b/src/tests/rust_guests/simpleguest/src/main.rs @@ -47,20 +47,20 @@ use hyperlight_guest::guest_function_definition::GuestFunctionDefinition; use hyperlight_guest::guest_function_register::register_function; use hyperlight_guest::host_function_call::{call_host_function, get_host_return_value}; use hyperlight_guest::memory::malloc; -use hyperlight_guest::{logging, MIN_STACK_ADDRESS}; -use log::{error, LevelFilter}; +use hyperlight_guest::{MIN_STACK_ADDRESS, logging}; +use log::{LevelFilter, error}; +use spin::Mutex; extern crate hyperlight_guest; -static mut BIGARRAY: [i32; 1024 * 1024] = [0; 1024 * 1024]; +static BIGARRAY: Mutex<[i32; 1024 * 1024]> = Mutex::new([0; 1024 * 1024]); fn set_static(_: &FunctionCall) -> Result> { - unsafe { - for val in BIGARRAY.iter_mut() { - *val = 1; - } - Ok(get_flatbuffer_result(BIGARRAY.len() as i32)) + let mut lock = BIGARRAY.lock(); + for val in lock.iter_mut() { + *val = 1; } + Ok(get_flatbuffer_result(lock.len() as i32)) } fn echo_double(function_call: &FunctionCall) -> Result> { @@ -354,7 +354,10 @@ fn print_ten_args(function_call: &FunctionCall) -> Result> { function_call.parameters.clone().unwrap()[8].clone(), function_call.parameters.clone().unwrap()[9].clone(), ) { - let message = format!("Message: arg1:{} arg2:{} arg3:{} arg4:{} arg5:{} arg6:{} arg7:{} arg8:{} arg9:{} arg10:{}.", arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10); + let message = format!( + "Message: arg1:{} arg2:{} arg3:{} arg4:{} arg5:{} arg6:{} arg7:{} arg8:{} arg9:{} arg10:{}.", + arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10 + ); print_output(&message) } else { Err(HyperlightGuestError::new( @@ -390,7 +393,10 @@ fn print_eleven_args(function_call: &FunctionCall) -> Result> { function_call.parameters.clone().unwrap()[9].clone(), function_call.parameters.clone().unwrap()[10].clone(), ) { - let message = format!("Message: arg1:{} arg2:{} arg3:{} arg4:{} arg5:{} arg6:{} arg7:{} arg8:{} arg9:{} arg10:{} arg11:{:.3}.", arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11); + let message = format!( + "Message: arg1:{} arg2:{} arg3:{} arg4:{} arg5:{} arg6:{} arg7:{} arg8:{} arg9:{} arg10:{} arg11:{:.3}.", + arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11 + ); print_output(&message) } else { Err(HyperlightGuestError::new( @@ -714,7 +720,7 @@ fn add(function_call: &FunctionCall) -> Result> { } } -#[no_mangle] +#[unsafe(no_mangle)] pub extern "C" fn hyperlight_main() { let set_static_def = GuestFunctionDefinition::new( "SetStatic".to_string(), @@ -1110,7 +1116,7 @@ pub extern "C" fn hyperlight_main() { register_function(trigger_exception_def); } -#[no_mangle] +#[unsafe(no_mangle)] pub fn guest_dispatch_function(function_call: FunctionCall) -> Result> { // This test checks the stack behavior of the input/output buffer // by calling the host before serializing the function call. @@ -1168,7 +1174,7 @@ fn fuzz_host_function(func: FunctionCall) -> Result> { return Err(HyperlightGuestError::new( ErrorCode::GuestFunctionParameterTypeMismatch, "Invalid parameters passed to fuzz_host_function".to_string(), - )) + )); } }; call_host_function(&host_func_name, Some(params), func.expected_return_type)