solana_accounts_db/tiered_storage/mmap_utils.rs
1use {
2 crate::{accounts_file::ALIGN_BOUNDARY_OFFSET, u64_align},
3 log::*,
4 memmap2::Mmap,
5 std::io::Result as IoResult,
6};
7
8/// Borrows a value of type `T` from `mmap`
9///
10/// Type T must be plain ol' data to ensure no undefined behavior.
11pub fn get_pod<T: bytemuck::AnyBitPattern>(mmap: &Mmap, offset: usize) -> IoResult<(&T, usize)> {
12 // SAFETY: Since T is AnyBitPattern, it is safe to cast bytes to T.
13 unsafe { get_type::<T>(mmap, offset) }
14}
15
16/// Borrows a value of type `T` from `mmap`
17///
18/// Prefer `get_pod()` when possible, because `get_type()` may cause undefined behavior.
19///
20/// # Safety
21///
22/// Caller must ensure casting bytes to T is safe.
23/// Refer to the Safety sections in std::slice::from_raw_parts()
24/// and bytemuck's Pod and AnyBitPattern for more information.
25pub unsafe fn get_type<T>(mmap: &Mmap, offset: usize) -> IoResult<(&T, usize)> {
26 let (data, next) = get_slice(mmap, offset, std::mem::size_of::<T>())?;
27 let ptr = data.as_ptr().cast();
28 debug_assert!(ptr as usize % std::mem::align_of::<T>() == 0);
29 // SAFETY: The caller ensures it is safe to cast bytes to T,
30 // we ensure the size is safe by querying T directly,
31 // and we just checked above to ensure the ptr is aligned for T.
32 Ok((unsafe { &*ptr }, next))
33}
34
35/// Get a reference to the data at `offset` of `size` bytes if that slice
36/// doesn't overrun the internal buffer. Otherwise return an Error.
37/// Also return the offset of the first byte after the requested data that
38/// falls on a 64-byte boundary.
39pub fn get_slice(mmap: &Mmap, offset: usize, size: usize) -> IoResult<(&[u8], usize)> {
40 let (next, overflow) = offset.overflowing_add(size);
41 if overflow || next > mmap.len() {
42 error!(
43 "Requested offset {} and size {} while mmap only has length {}",
44 offset,
45 size,
46 mmap.len()
47 );
48 return Err(std::io::Error::new(
49 std::io::ErrorKind::AddrNotAvailable,
50 "Requested offset and data length exceeds the mmap slice",
51 ));
52 }
53 let data = &mmap[offset..next];
54 let next = u64_align!(next);
55 let ptr = data.as_ptr();
56
57 // SAFETY: The Mmap ensures the bytes are safe the read, and we just checked
58 // to ensure we don't read past the end of the internal buffer.
59 Ok((unsafe { std::slice::from_raw_parts(ptr, size) }, next))
60}