Skip to main content

solana_program_runtime/
memory.rs

1//! Memory translation utilities.
2
3use {
4    crate::abi::ABI, solana_sbpf::memory_region::MemoryMapping,
5    solana_transaction_context::vm_slice::VmSlice,
6};
7
8/// Error types for memory translation operations.
9#[derive(Debug, thiserror::Error, PartialEq, Eq, Clone)]
10pub enum MemoryTranslationError {
11    #[error("Unaligned pointer")]
12    UnalignedPointer,
13    #[error("InvalidLength")]
14    InvalidLength,
15}
16
17// Do not use this directly
18#[macro_export]
19macro_rules! translate_inner {
20    ($memory_mapping:expr, $map:ident, $access_type:expr, $vm_addr:expr, $len:expr $(,)?) => {
21        Result::<$crate::solana_sbpf::memory_region::HostBuffer, Box<dyn std::error::Error>>::from(
22            $memory_mapping
23                .$map($access_type, $vm_addr, $len)
24                .map_err(|err| err.into()),
25        )
26    };
27}
28
29// Do not use this directly
30#[macro_export]
31macro_rules! translate_type_inner {
32    ($memory_mapping:expr, AccessType::Store, $vm_addr:expr, $T:ty, $abi:expr $(,)?) => {{
33        let host_addr = $crate::translate_inner!(
34            $memory_mapping,
35            map,
36            $crate::solana_sbpf::memory_region::AccessType::Store,
37            $vm_addr,
38            size_of::<$T>() as u64
39        )?;
40        let ptr = host_addr.ptr_mut().cast::<$T>();
41        if $abi == $crate::abi::ABI::V1 && !ptr.is_aligned() {
42            Err($crate::memory::MemoryTranslationError::UnalignedPointer.into())
43        } else {
44            Ok(unsafe { ptr.as_mut_unchecked() })
45        }
46    }};
47    ($memory_mapping:expr, AccessType::Load, $vm_addr:expr, $T:ty, $abi:expr $(,)?) => {{
48        let host_addr = $crate::translate_inner!(
49            $memory_mapping,
50            map,
51            $crate::solana_sbpf::memory_region::AccessType::Load,
52            $vm_addr,
53            size_of::<$T>() as u64
54        )?;
55        let ptr = host_addr.ptr().cast::<$T>();
56        if $abi == $crate::abi::ABI::V1 && !ptr.is_aligned() {
57            Err($crate::memory::MemoryTranslationError::UnalignedPointer.into())
58        } else {
59            Ok(unsafe { ptr.as_ref_unchecked() })
60        }
61    }};
62}
63
64// Do not use this directly
65#[macro_export]
66macro_rules! translate_slice_inner {
67    ($memory_mapping:expr, AccessType::Store, $vm_addr:expr, $len:expr, $T:ty, $abi:expr $(,)?) => {{
68        if $len == 0 {
69            Ok(std::ptr::slice_from_raw_parts_mut(
70                std::ptr::dangling_mut::<$T>(),
71                0,
72            ))
73        } else {
74            let total_size = $len.saturating_mul(size_of::<$T>() as u64);
75            if isize::try_from(total_size).is_err() {
76                Err($crate::memory::MemoryTranslationError::InvalidLength.into())
77            } else {
78                match $crate::translate_inner!(
79                    $memory_mapping,
80                    map,
81                    $crate::solana_sbpf::memory_region::AccessType::Store,
82                    $vm_addr,
83                    total_size
84                ) {
85                    Err(e) => Err(e),
86                    Ok(host_buf)
87                        if $abi == $crate::abi::ABI::V1
88                            && !host_buf.ptr().cast::<$T>().is_aligned() =>
89                    {
90                        Err($crate::memory::MemoryTranslationError::UnalignedPointer.into())
91                    }
92                    Ok(host_buf) => Ok(std::ptr::slice_from_raw_parts_mut(
93                        host_buf.ptr_mut().cast(),
94                        $len as usize,
95                    )),
96                }
97            }
98        }
99    }};
100    ($memory_mapping:expr, AccessType::Load, $vm_addr:expr, $len:expr, $T:ty, $abi:expr $(,)?) => {{
101        if $len == 0 {
102            Ok(std::ptr::slice_from_raw_parts(
103                std::ptr::dangling_mut::<$T>(),
104                0,
105            ))
106        } else {
107            let total_size = $len.saturating_mul(size_of::<$T>() as u64);
108            if isize::try_from(total_size).is_err() {
109                Err($crate::memory::MemoryTranslationError::InvalidLength.into())
110            } else {
111                match $crate::translate_inner!(
112                    $memory_mapping,
113                    map,
114                    $crate::solana_sbpf::memory_region::AccessType::Load,
115                    $vm_addr,
116                    total_size
117                ) {
118                    Err(e) => Err(e),
119                    Ok(host_buf)
120                        if $abi == $crate::abi::ABI::V1
121                            && !host_buf.ptr().cast::<$T>().is_aligned() =>
122                    {
123                        Err($crate::memory::MemoryTranslationError::UnalignedPointer.into())
124                    }
125                    Ok(host_buf) => Ok(std::ptr::slice_from_raw_parts(
126                        host_buf.ptr().cast(),
127                        $len as usize,
128                    )),
129                }
130            }
131        }
132    }};
133}
134
135pub fn translate_type<'a, T>(
136    memory_mapping: &MemoryMapping,
137    vm_addr: u64,
138    abi: ABI,
139) -> Result<&'a T, Box<dyn std::error::Error>> {
140    translate_type_inner!(memory_mapping, AccessType::Load, vm_addr, T, abi)
141}
142
143pub fn translate_slice<T>(
144    memory_mapping: &MemoryMapping,
145    vm_addr: u64,
146    len: u64,
147    abi: ABI,
148) -> Result<&[T], Box<dyn std::error::Error>> {
149    translate_slice_inner!(memory_mapping, AccessType::Load, vm_addr, len, T, abi).map(
150        |value| unsafe {
151            // SAFETY: `translate_slice_inner` is guaranteed to return a dereferenceable memory region.
152            // This is producing a shared/read-only slice to the memory, so the uniqueness invariants
153            // aren't relevant.
154            &*value
155        },
156    )
157}
158
159/// CPI-specific version with intentionally different lifetime signature.
160/// This version is missing lifetime 'a of the return type in the parameter &MemoryMapping.
161pub fn translate_type_mut_for_cpi<'a, T>(
162    memory_mapping: &MemoryMapping,
163    vm_addr: u64,
164    abi: ABI,
165) -> Result<&'a mut T, Box<dyn std::error::Error>> {
166    translate_type_inner!(memory_mapping, AccessType::Store, vm_addr, T, abi)
167}
168
169/// CPI-specific version with intentionally different lifetime signature.
170/// This version is missing lifetime 'a of the return type in the parameter &MemoryMapping.
171///
172/// # Safety
173///
174/// * The caller must ensure that this function does not violate mutable reference uniqueness
175///   constraints;
176/// * The caller must ensure that the lifetime of the returned slice does not outlive the backing
177///   data.
178pub unsafe fn translate_slice_mut_for_cpi<'a, T>(
179    memory_mapping: &MemoryMapping,
180    vm_addr: u64,
181    len: u64,
182    abi: ABI,
183) -> Result<&'a mut [T], Box<dyn std::error::Error>> {
184    translate_slice_inner!(memory_mapping, AccessType::Store, vm_addr, len, T, abi).map(
185        |p| unsafe {
186            // SAFETY: the invariants for producing mutable references delegated to the callers.
187            &mut *p
188        },
189    )
190}
191
192pub fn translate_vm_slice<'a, T>(
193    slice: &VmSlice<T>,
194    memory_mapping: &'a MemoryMapping,
195    abi: ABI,
196) -> Result<&'a [T], Box<dyn std::error::Error>> {
197    translate_slice::<T>(memory_mapping, slice.ptr(), slice.len(), abi)
198}
199
200#[cfg(test)]
201mod tests {
202    use {
203        super::*,
204        solana_sbpf::{
205            aligned_memory::AlignedMemory, ebpf::HOST_ALIGN, memory_region::MemoryRegion,
206            program::SBPFVersion, vm::Config,
207        },
208        test_case::test_case,
209    };
210
211    const VM_ADDR: u64 = 0x100000000;
212
213    #[test_case(ABI::V0, true; "abi_v0_allows_unaligned")]
214    #[test_case(ABI::V1, false; "abi_v1_rejects_unaligned")]
215    fn test_translate_unaligned_pointer(abi: ABI, is_allowed: bool) {
216        let mut memory = AlignedMemory::<HOST_ALIGN>::zero_filled(32);
217        let config = Config {
218            aligned_memory_mapping: false,
219            ..Config::default()
220        };
221        let regions = vec![MemoryRegion::new(&mut memory, VM_ADDR)];
222        let mapping = unsafe { MemoryMapping::new(regions, &config, SBPFVersion::V3).unwrap() };
223        let unaligned = VM_ADDR + 1;
224
225        let results = [
226            translate_slice::<u64>(&mapping, unaligned, 1, abi).map(|_| ()),
227            unsafe { translate_slice_mut_for_cpi::<u64>(&mapping, unaligned, 1, abi) }.map(|_| ()),
228        ];
229        for result in results {
230            assert_eq!(result.is_ok(), is_allowed);
231        }
232
233        // Aligned pointers translate under every ABI.
234        assert!(translate_type::<u64>(&mapping, VM_ADDR, abi).is_ok());
235        assert!(translate_type_mut_for_cpi::<u64>(&mapping, VM_ADDR, abi).is_ok());
236        assert!(translate_slice::<u64>(&mapping, VM_ADDR, 1, abi).is_ok());
237    }
238
239    #[test]
240    fn test_translate_type_rejects_unaligned_pointer_abi_v1() {
241        let mut memory = AlignedMemory::<HOST_ALIGN>::zero_filled(32);
242        let config = Config {
243            aligned_memory_mapping: false,
244            ..Config::default()
245        };
246        let regions = vec![MemoryRegion::new(&mut memory, VM_ADDR)];
247        let mapping = unsafe { MemoryMapping::new(regions, &config, SBPFVersion::V3).unwrap() };
248        let unaligned = VM_ADDR + 1;
249
250        assert!(translate_type::<u64>(&mapping, unaligned, ABI::V1).is_err());
251        assert!(translate_type_mut_for_cpi::<u64>(&mapping, unaligned, ABI::V1).is_err());
252    }
253}