Skip to content
Merged
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
419 changes: 202 additions & 217 deletions litebox_common_linux/src/lib.rs

Large diffs are not rendered by default.

29 changes: 17 additions & 12 deletions litebox_common_linux/src/mm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,10 @@ use litebox::{
mm::linux::{
CreatePagesFlags, MappingError, NonZeroAddress, NonZeroPageSize, PAGE_SIZE, VmemUnmapError,
},
platform::{RawConstPointer, page_mgmt::DeallocationError},
platform::page_mgmt::DeallocationError,
};

use crate::{MRemapFlags, MapFlags, ProtFlags, errno::Errno};
use crate::{MRemapFlags, MapFlags, ProtFlags, UserPtrMut, errno::Errno};

const PAGE_MASK: usize = !(PAGE_SIZE - 1);

Expand All @@ -25,8 +25,9 @@ pub fn do_mmap<
prot: ProtFlags,
flags: MapFlags,
ensure_space_after: bool,
op: impl FnOnce(Platform::RawMutPointer<u8>) -> Result<usize, litebox::mm::linux::MappingError>,
) -> Result<Platform::RawMutPointer<u8>, litebox::mm::linux::MappingError> {
op: impl FnOnce(UserPtrMut<u8>) -> Result<usize, litebox::mm::linux::MappingError>,
) -> Result<UserPtrMut<u8>, litebox::mm::linux::MappingError> {
let op = |p: Platform::RawMutPointer<u8>| op(UserPtrMut::from_platform_ptr::<Platform>(p));
let flags = {
let mut create_flags = CreatePagesFlags::empty();
// MAP_FIXED_NOREPLACE implies MAP_FIXED behavior (exact address, not a hint)
Expand Down Expand Up @@ -82,6 +83,7 @@ pub fn do_mmap<
}
}
}
.map(UserPtrMut::from_platform_ptr::<Platform>)
}

/// Handle syscall `munmap`
Expand All @@ -91,7 +93,7 @@ pub fn sys_munmap<
+ litebox::platform::PageManagementProvider<{ litebox::mm::linux::PAGE_SIZE }>,
>(
pm: &litebox::mm::PageManager<Platform, { litebox::mm::linux::PAGE_SIZE }>,
addr: Platform::RawMutPointer<u8>,
addr: UserPtrMut<u8>,
len: usize,
) -> Result<(), Errno> {
if addr.as_usize() & !PAGE_MASK != 0 {
Expand All @@ -107,7 +109,7 @@ pub fn sys_munmap<
return Err(Errno::EINVAL);
}

match unsafe { pm.remove_pages(addr, aligned_len) } {
match unsafe { pm.remove_pages(addr.to_platform_ptr::<Platform>(), aligned_len) } {
Err(VmemUnmapError::UnAligned) => Err(Errno::EINVAL),
Err(VmemUnmapError::UnmapError(e)) => match e {
DeallocationError::Unaligned => Err(Errno::EINVAL),
Expand All @@ -126,7 +128,7 @@ pub fn sys_mprotect<
+ litebox::platform::PageManagementProvider<{ litebox::mm::linux::PAGE_SIZE }>,
>(
pm: &litebox::mm::PageManager<Platform, { litebox::mm::linux::PAGE_SIZE }>,
addr: Platform::RawMutPointer<u8>,
addr: UserPtrMut<u8>,
len: usize,
prot: ProtFlags,
) -> Result<(), Errno> {
Expand All @@ -137,6 +139,7 @@ pub fn sys_mprotect<
return Ok(());
}

let addr = addr.to_platform_ptr::<Platform>();
match prot {
ProtFlags::PROT_READ_EXEC => unsafe { pm.make_pages_executable(addr, len) },
ProtFlags::PROT_READ_WRITE => unsafe { pm.make_pages_writable(addr, len) },
Expand All @@ -160,12 +163,12 @@ pub fn sys_mremap<
+ litebox::platform::PageManagementProvider<{ litebox::mm::linux::PAGE_SIZE }>,
>(
pm: &litebox::mm::PageManager<Platform, { litebox::mm::linux::PAGE_SIZE }>,
old_addr: Platform::RawMutPointer<u8>,
old_addr: UserPtrMut<u8>,
old_size: usize,
new_size: usize,
flags: MRemapFlags,
_new_addr: usize,
) -> Result<Platform::RawMutPointer<u8>, Errno> {
) -> Result<UserPtrMut<u8>, Errno> {
if flags.intersects(
(MRemapFlags::MREMAP_FIXED | MRemapFlags::MREMAP_MAYMOVE | MRemapFlags::MREMAP_DONTUNMAP)
.complement(),
Expand Down Expand Up @@ -207,12 +210,13 @@ pub fn sys_mremap<

unsafe {
pm.remap_pages(
old_addr,
old_addr.to_platform_ptr::<Platform>(),
old_size,
new_size,
flags.contains(MRemapFlags::MREMAP_MAYMOVE),
)
}
.map(UserPtrMut::from_platform_ptr::<Platform>)
.map_err(Errno::from)
}

Expand All @@ -222,7 +226,7 @@ pub fn sys_brk<
+ litebox::platform::PageManagementProvider<{ litebox::mm::linux::PAGE_SIZE }>,
>(
pm: &litebox::mm::PageManager<Platform, { litebox::mm::linux::PAGE_SIZE }>,
addr: Platform::RawMutPointer<u8>,
addr: UserPtrMut<u8>,
) -> Result<usize, Errno> {
unsafe { pm.brk(addr.as_usize()) }.map_err(Errno::from)
}
Expand All @@ -233,7 +237,7 @@ pub fn sys_madvise<
+ litebox::platform::PageManagementProvider<{ litebox::mm::linux::PAGE_SIZE }>,
>(
pm: &litebox::mm::PageManager<Platform, { litebox::mm::linux::PAGE_SIZE }>,
addr: Platform::RawMutPointer<u8>,
addr: UserPtrMut<u8>,
len: usize,
advice: crate::MadviseBehavior,
) -> Result<(), Errno> {
Expand All @@ -252,6 +256,7 @@ pub fn sys_madvise<
return Err(Errno::EINVAL);
};

let addr = addr.to_platform_ptr::<Platform>();
match advice {
crate::MadviseBehavior::Normal
| crate::MadviseBehavior::DontFork
Expand Down
230 changes: 230 additions & 0 deletions litebox_common_linux/src/user_pointers.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,230 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.

//! Address-only user pointer types.
//!
//! These wrap a bare `usize` address and, unlike
//! [`litebox::platform::RawConstPointer`]/[`litebox::platform::RawMutPointer`],
//! carry no [`RawPointerProvider`] (`Platform`) parameter. This keeps `Platform`
//! from being viral across every type that merely *stores* a user pointer value.
//! Memory is accessed by converting back to the platform pointer type via
//! [`UserPtr::to_platform_ptr`]/[`UserPtrMut::to_platform_ptr`] (or the
//! convenience access methods), which take the platform as an explicit witness
//! `P`.

use litebox::platform::{RawConstPointer, RawMutPointer, RawPointerProvider};
use zerocopy::{FromBytes, IntoBytes};

/// A user-space const pointer represented purely as an address (`usize`).
///
/// Unlike [`litebox::platform::RawConstPointer`], this type carries no
/// [`RawPointerProvider`] (`Platform`) parameter: it only *stores* the address
/// of a user pointer. Memory is accessed by converting back to the platform
/// pointer type via the [`Self::read_at_offset`]/[`Self::to_owned_slice`]
/// methods, which take the platform as an explicit witness `P`.
///
/// This keeps `Platform` from being viral across every type that merely holds a
/// user pointer value.
// NOTE: We explicitly write the `T: Sized` bound to document that these need to
// be "thin" pointers; "fat" pointers (i.e., pointers to DSTs) are unsupported.
#[derive(FromBytes, IntoBytes)]
#[repr(transparent)]
pub struct UserPtr<T: Sized> {
/// An exposed-provenance address of the pointer.
addr: usize,
/// Note: This keeps user pointers `!Send + !Sync`; see
/// <https://github.com/microsoft/litebox/issues/431>.
_phantom: core::marker::PhantomData<*const T>,
}
Comment thread
jaybosamiya-ms marked this conversation as resolved.

impl<T> UserPtr<T> {
/// Create a pointer from a raw address.
pub fn from_usize(addr: usize) -> Self {
Self {
addr,
_phantom: core::marker::PhantomData,
}
}

/// Create a pointer from a native `*const T`, exposing its provenance.
pub fn from_ptr(ptr: *const T) -> Self {
Self::from_usize(ptr.expose_provenance())
}

/// Get the address of the pointer as a `usize`.
pub fn as_usize(&self) -> usize {
self.addr
}

/// Whether this pointer's address is null (zero).
pub fn is_null(&self) -> bool {
self.addr == 0
}

/// Reinterpret this pointer as pointing to a different type `U`.
pub fn cast<U>(self) -> UserPtr<U> {
UserPtr::from_usize(self.addr)
}
}

impl<T> Clone for UserPtr<T> {
fn clone(&self) -> Self {
*self
}
}
impl<T> Copy for UserPtr<T> {}
impl<T> core::fmt::Debug for UserPtr<T> {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.debug_tuple("UserPtr").field(&self.addr).finish()
}
}

impl<T: FromBytes> UserPtr<T> {
/// Convert platform `P`'s const pointer type into an address-only pointer.
pub fn from_platform_ptr<P: RawPointerProvider>(ptr: P::RawConstPointer<T>) -> Self {
Self::from_usize(ptr.as_usize())
}

/// Convert this address-only pointer into platform `P`'s const pointer type,
/// through which memory can actually be accessed.
pub fn to_platform_ptr<P: RawPointerProvider>(self) -> P::RawConstPointer<T> {
<P::RawConstPointer<T> as RawConstPointer<T>>::from_usize(self.addr)
}

/// See [`RawConstPointer::read_at_offset`].
pub fn read_at_offset<P: RawPointerProvider>(self, count: isize) -> Option<T> {
self.to_platform_ptr::<P>().read_at_offset(count)
}

/// See [`RawConstPointer::to_owned_slice`].
pub fn to_owned_slice<P: RawPointerProvider>(
self,
len: usize,
) -> Option<alloc::boxed::Box<[T]>> {
self.to_platform_ptr::<P>().to_owned_slice(len)
}
}

impl UserPtr<core::ffi::c_char> {
/// See [`RawConstPointer::to_cstring`].
pub fn to_cstring<P: RawPointerProvider>(self) -> Option<alloc::ffi::CString> {
self.to_platform_ptr::<P>().to_cstring()
}
}

/// A user-space mutable pointer represented purely as an address (`usize`).
///
/// The mutable counterpart of [`UserPtr`]. See [`UserPtr`] for the rationale.
// NOTE: We explicitly write the `T: Sized` bound to document that these need to
// be "thin" pointers; "fat" pointers (i.e., pointers to DSTs) are unsupported.
#[derive(FromBytes, IntoBytes)]
#[repr(transparent)]
pub struct UserPtrMut<T: Sized> {
/// An exposed-provenance address of the pointer.
addr: usize,
/// Note: This keeps user pointers `!Send + !Sync`; see
/// <https://github.com/microsoft/litebox/issues/431>.
_phantom: core::marker::PhantomData<*mut T>,
}

impl<T> UserPtrMut<T> {
/// Create a pointer from a raw address.
pub fn from_usize(addr: usize) -> Self {
Self {
addr,
_phantom: core::marker::PhantomData,
}
}

/// Create a pointer from a native `*mut T`, exposing its provenance.
pub fn from_ptr(ptr: *mut T) -> Self {
Self::from_usize(ptr.expose_provenance())
}

/// Get the address of the pointer as a `usize`.
pub fn as_usize(&self) -> usize {
self.addr
}

/// Whether this pointer's address is null (zero).
pub fn is_null(&self) -> bool {
self.addr == 0
}

/// Reinterpret this pointer as pointing to a different type `U`.
pub fn cast<U>(self) -> UserPtrMut<U> {
UserPtrMut::from_usize(self.addr)
}
}

impl<T> Clone for UserPtrMut<T> {
fn clone(&self) -> Self {
*self
}
}
impl<T> Copy for UserPtrMut<T> {}
impl<T> core::fmt::Debug for UserPtrMut<T> {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.debug_tuple("UserPtrMut").field(&self.addr).finish()
}
}

impl<T: FromBytes + IntoBytes> UserPtrMut<T> {
/// Convert platform `P`'s mutable pointer type into an address-only pointer.
pub fn from_platform_ptr<P: RawPointerProvider>(ptr: P::RawMutPointer<T>) -> Self {
Self::from_usize(ptr.as_usize())
}

/// Convert this address-only pointer into platform `P`'s mutable pointer type,
/// through which memory can actually be accessed.
pub fn to_platform_ptr<P: RawPointerProvider>(self) -> P::RawMutPointer<T> {
<P::RawMutPointer<T> as RawConstPointer<T>>::from_usize(self.addr)
}

/// See [`RawConstPointer::read_at_offset`].
pub fn read_at_offset<P: RawPointerProvider>(self, count: isize) -> Option<T> {
self.to_platform_ptr::<P>().read_at_offset(count)
}

/// See [`RawConstPointer::to_owned_slice`].
pub fn to_owned_slice<P: RawPointerProvider>(
self,
len: usize,
) -> Option<alloc::boxed::Box<[T]>> {
self.to_platform_ptr::<P>().to_owned_slice(len)
}

/// See [`RawMutPointer::write_at_offset`].
#[must_use]
pub fn write_at_offset<P: RawPointerProvider>(self, count: isize, value: T) -> Option<()> {
self.to_platform_ptr::<P>().write_at_offset(count, value)
}

/// See [`RawMutPointer::write_slice_at_offset`].
#[must_use]
pub fn write_slice_at_offset<P: RawPointerProvider>(
self,
count: isize,
values: &[T],
) -> Option<()>
where
T: Clone,
{
self.to_platform_ptr::<P>()
.write_slice_at_offset(count, values)
}

/// See [`RawMutPointer::copy_from_slice`].
#[must_use]
pub fn copy_from_slice<P: RawPointerProvider>(
self,
start_offset: usize,
buf: &[T],
) -> Option<()>
where
T: Copy,
{
self.to_platform_ptr::<P>()
.copy_from_slice(start_offset, buf)
}
}
Loading
Loading