Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 36 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

13 changes: 10 additions & 3 deletions src/hyperlight_common/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,16 @@ Hyperlight's components common to host and guest.
workspace = true

[dependencies]
flatbuffers = { version = "25.12.19", default-features = false }
arbitrary = {version = "1.4.2", optional = true, features = ["derive"]}
anyhow = { version = "1.0.102", default-features = false }
bitflags = "2.10.0"
bytemuck = { version = "1.24", features = ["derive"] }
flatbuffers = { version = "25.12.19", default-features = false }
log = "0.4.29"
tracing = { version = "0.1.44", optional = true }
arbitrary = {version = "1.4.2", optional = true, features = ["derive"]}
smallvec = "1.15.1"
spin = "0.10.0"
thiserror = { version = "2.0.18", default-features = false }
tracing = { version = "0.1.44", optional = true }
tracing-core = { version = "0.1.36", default-features = false }

[features]
Expand All @@ -33,6 +36,10 @@ mem_profile = []
std = ["thiserror/std", "log/std", "tracing/std"]
nanvix-unstable = []

[dev-dependencies]
quickcheck = "1.0.3"
rand = "0.9.2"

[lib]
bench = false # see https://bheisler.github.io/criterion.rs/book/faq.html#cargo-bench-gives-unrecognized-option-errors-for-valid-command-line-options
doctest = false # reduce noise in test output
5 changes: 4 additions & 1 deletion src/hyperlight_common/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ limitations under the License.
#![cfg_attr(not(any(test, debug_assertions)), warn(clippy::expect_used))]
#![cfg_attr(not(any(test, debug_assertions)), warn(clippy::unwrap_used))]
// We use Arbitrary during fuzzing, which requires std
#![cfg_attr(not(feature = "fuzzing"), no_std)]
#![cfg_attr(not(any(feature = "fuzzing", test, miri)), no_std)]

extern crate alloc;

Expand Down Expand Up @@ -50,3 +50,6 @@ pub mod vmem;

/// ELF note types for embedding hyperlight version metadata in guest binaries.
pub mod version_note;

/// cbindgen:ignore
pub mod virtq;
167 changes: 167 additions & 0 deletions src/hyperlight_common/src/virtq/access.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,167 @@
/*
Copyright 2026 The Hyperlight Authors.

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

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

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

//! Memory Access Traits for Virtqueue Operations
//!
//! This module defines the [`MemOps`] trait that abstracts memory access patterns
//! required by the virtqueue implementation. This allows the virtqueue code to
//! work with different memory backends e.g. Host vs Guest.

use alloc::sync::Arc;

use bytemuck::Pod;

/// Backend-provided memory access for virtqueue.
///
/// # Safety
///
/// Implementations must ensure that:
/// - Pointers passed to methods are valid for the duration of the call
/// - Memory ordering guarantees are upheld as documented
/// - Reads and writes don't cause undefined behavior (alignment, validity)
///
/// [`RingProducer`]: super::RingProducer
/// [`RingConsumer`]: super::RingConsumer
pub trait MemOps {
type Error;

/// Read bytes from physical memory.
///
/// Used for reading buffer contents pointed to by descriptors.
///
/// # Arguments
///
/// * `addr` - Guest physical address to read from
/// * `dst` - Destination buffer to fill
///
/// # Returns
///
/// Number of bytes actually read (should equal `dst.len()` on success).
///
/// # Safety
///
/// The caller must ensure `paddr` is valid and points to at least `dst.len()` bytes.
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit:

Suggested change
/// The caller must ensure `paddr` is valid and points to at least `dst.len()` bytes.
/// The caller must ensure `addr` is valid and points to at least `dst.len()` bytes.

fn read(&self, addr: u64, dst: &mut [u8]) -> Result<usize, Self::Error>;

/// Write bytes to physical memory.
///
/// # Arguments
///
/// * `addr` - address to write to
/// * `src` - Source data to write
///
/// # Returns
///
/// Number of bytes actually written (should equal `src.len()` on success).
///
/// # Safety
///
/// The caller must ensure `paddr` is valid and points to at least `src.len()` bytes.
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit:

Suggested change
/// The caller must ensure `paddr` is valid and points to at least `src.len()` bytes.
/// The caller must ensure `addr` is valid and points to at least `src.len()` bytes.

fn write(&self, addr: u64, src: &[u8]) -> Result<usize, Self::Error>;

/// Load a u16 with acquire semantics.
///
/// # Safety
///
/// `addr` must translate to a valid, aligned `AtomicU16` in shared memory.
fn load_acquire(&self, addr: u64) -> Result<u16, Self::Error>;

/// Store a u16 with release semantics.
///
/// # Safety
///
/// `addr` must translate to a valid `AtomicU16` in shared memory.
fn store_release(&self, addr: u64, val: u16) -> Result<(), Self::Error>;

/// Get a direct read-only slice into shared memory.
///
/// # Safety
///
/// The caller must ensure:
/// - `addr` is valid and points to at least `len` bytes.
/// - The memory region is not concurrently modified for the lifetime of
/// the returned slice. Caller must uphold this via protocol-level
/// synchronisation, e.g. descriptor ownership transfer.
///
/// See also [`BufferOwner`]: super::BufferOwner
unsafe fn as_slice(&self, addr: u64, len: usize) -> Result<&[u8], Self::Error>;

/// Get a direct mutable slice into shared memory.
///
/// # Safety
///
/// The caller must ensure:
/// - `addr` is valid and points to at least `len` bytes.
/// - No other references (shared or mutable) to this memory region exist
/// for the lifetime of the returned slice.
/// - Protocol-level synchronisation (e.g. descriptor ownership) guarantees
/// exclusive access.
#[allow(clippy::mut_from_ref)]
unsafe fn as_mut_slice(&self, addr: u64, len: usize) -> Result<&mut [u8], Self::Error>;

/// Read a Pod type at the given pointer.
///
/// # Safety
///
/// The caller must ensure `addr` is valid, aligned, and translates to initialized memory.
fn read_val<T: Pod>(&self, addr: u64) -> Result<T, Self::Error> {
let mut val = T::zeroed();
let bytes = bytemuck::bytes_of_mut(&mut val);

self.read(addr, bytes)?;
Ok(val)
}

/// Write a Pod type at the given pointer.
///
/// # Safety
///
/// The caller ensures that `ptr` is valid.
fn write_val<T: Pod>(&self, addr: u64, val: T) -> Result<(), Self::Error> {
let bytes = bytemuck::bytes_of(&val);
self.write(addr, bytes)?;
Ok(())
}
}

impl<T: MemOps> MemOps for Arc<T> {
type Error = T::Error;

fn read(&self, addr: u64, dst: &mut [u8]) -> Result<usize, Self::Error> {
(**self).read(addr, dst)
}

fn write(&self, addr: u64, src: &[u8]) -> Result<usize, Self::Error> {
(**self).write(addr, src)
}

fn load_acquire(&self, addr: u64) -> Result<u16, Self::Error> {
(**self).load_acquire(addr)
}

fn store_release(&self, addr: u64, val: u16) -> Result<(), Self::Error> {
(**self).store_release(addr, val)
}

unsafe fn as_slice(&self, addr: u64, len: usize) -> Result<&[u8], Self::Error> {
unsafe { (**self).as_slice(addr, len) }
}

#[allow(clippy::mut_from_ref)]
unsafe fn as_mut_slice(&self, addr: u64, len: usize) -> Result<&mut [u8], Self::Error> {
unsafe { (**self).as_mut_slice(addr, len) }
}
}
Loading
Loading