Skip to main content

graphics/call/
transport.rs

1//! How pointer, string and buffer arguments reach the executor.
2//!
3//! A call carries up to seven words. Scalars are used as they are; a pointer
4//! word is an address the transport understands. Wasm passes offsets into a
5//! guest's linear memory, which the transport bounds-checks and translates;
6//! native code passes host pointers directly, since native code is trusted.
7//! The executor never dereferences an address itself.
8//!
9//! All multi-byte values behind an address are little-endian. Xila's targets
10//! and Wasm are little-endian, so a native transport reads them in place.
11
12use super::error::{Error, Result};
13use core::{ffi::CStr, marker::PhantomData};
14
15/// One argument word: as wide as the host's pointers, so a call costs no
16/// double-word arithmetic on a 32-bit target. A Wasm guest's 32-bit or 64-bit
17/// word fits, since guests with 64-bit memory only run on 64-bit hosts.
18pub type Word = usize;
19
20/// Argument memory of one caller.
21pub trait Transport {
22    /// Width in bits of the caller's pointer-sized word, 32 or 64, never wider
23    /// than the host's `usize`. It tells a zero-extended 32-bit word from a
24    /// sign-extended 64-bit one.
25    fn word_bits(&self) -> u32;
26
27    /// Borrow `length` bytes at `address`. A null address is valid only for an
28    /// empty range.
29    fn bytes(&self, address: Word, length: usize) -> Result<&[u8]>;
30
31    /// Exclusively borrow `length` bytes at `address`.
32    fn bytes_mut(&mut self, address: Word, length: usize) -> Result<&mut [u8]>;
33
34    /// Borrow the NUL-terminated string at `address` without copying it.
35    /// A string longer than `limit` bytes, NUL included, is `ResourceLimit`;
36    /// a null address or a string that leaves memory is `InvalidMemory`.
37    fn c_string(&self, address: Word, limit: usize) -> Result<&CStr>;
38}
39
40/// A scalar with a fixed little-endian encoding behind an address.
41pub(crate) trait Scalar: Copy {
42    const SIZE: usize;
43    fn decode(bytes: &[u8]) -> Self;
44    fn encode(self, bytes: &mut [u8]);
45}
46
47macro_rules! scalars {
48    ($($ty:ty),*) => { $(
49        impl Scalar for $ty {
50            const SIZE: usize = core::mem::size_of::<$ty>();
51            fn decode(bytes: &[u8]) -> Self {
52                Self::from_le_bytes(bytes.try_into().expect("exact scalar size"))
53            }
54            fn encode(self, bytes: &mut [u8]) {
55                bytes.copy_from_slice(&self.to_le_bytes());
56            }
57        }
58    )* };
59}
60scalars!(u8, u16, u32, i32);
61
62fn offset(address: Word, delta: usize) -> Result<Word> {
63    address
64        .checked_add(delta as Word)
65        .ok_or(Error::InvalidMemory)
66}
67
68/// Typed access built on the three required methods.
69impl dyn Transport + '_ {
70    pub(crate) fn word_size(&self) -> usize {
71        (self.word_bits() / 8) as usize
72    }
73
74    pub(crate) fn validate(&self, address: Word, length: usize) -> Result<()> {
75        self.bytes(address, length).map(|_| ())
76    }
77
78    pub(crate) fn read<T: Scalar>(&self, address: Word) -> Result<T> {
79        Ok(T::decode(self.bytes(address, T::SIZE)?))
80    }
81
82    pub(crate) fn write<T: Scalar>(&mut self, address: Word, value: T) -> Result<()> {
83        value.encode(self.bytes_mut(address, T::SIZE)?);
84        Ok(())
85    }
86
87    /// Write a result whose location `execute` validated before the call, so
88    /// the write cannot fail. A panic path per call site would cost code for
89    /// a case that only a broken transport can reach.
90    pub(crate) fn put<T: Scalar>(&mut self, address: Word, value: T) {
91        let written = self.write(address, value);
92        debug_assert!(written.is_ok(), "result location was validated");
93    }
94
95    /// A pointer-sized word.
96    pub(crate) fn read_word(&self, address: Word) -> Result<Word> {
97        let bytes = self.bytes(address, self.word_size())?;
98        let mut word = [0; size_of::<Word>()];
99        word[..bytes.len()].copy_from_slice(bytes);
100        Ok(Word::from_le_bytes(word))
101    }
102
103    pub(crate) fn put_word(&mut self, address: Word, value: Word) {
104        let size = self.word_size();
105        let written = self.bytes_mut(address, size);
106        debug_assert!(written.is_ok(), "result location was validated");
107        if let Ok(bytes) = written {
108            bytes.copy_from_slice(&value.to_le_bytes()[..size]);
109        }
110    }
111
112    /// Lazily decode `count` consecutive scalars.
113    pub(crate) fn values<T: Scalar>(&self, address: Word, count: usize) -> Result<Values<'_, T>> {
114        let length = count.checked_mul(T::SIZE).ok_or(Error::InvalidMemory)?;
115        Ok(Values {
116            bytes: self.bytes(address, length)?,
117            marker: PhantomData,
118        })
119    }
120
121    /// The `index`th scalar of a table.
122    pub(crate) fn read_at<T: Scalar>(&self, address: Word, index: usize) -> Result<T> {
123        self.read(offset(address, index * T::SIZE)?)
124    }
125}
126
127/// Scalars decoded one at a time from borrowed bytes.
128pub(crate) struct Values<'a, T> {
129    bytes: &'a [u8],
130    marker: PhantomData<T>,
131}
132
133impl<T: Scalar> Iterator for Values<'_, T> {
134    type Item = T;
135
136    fn next(&mut self) -> Option<T> {
137        if self.bytes.is_empty() {
138            return None;
139        }
140        let (value, rest) = self.bytes.split_at(T::SIZE);
141        self.bytes = rest;
142        Some(T::decode(value))
143    }
144
145    fn size_hint(&self) -> (usize, Option<usize>) {
146        let remaining = self.bytes.len() / T::SIZE;
147        (remaining, Some(remaining))
148    }
149}
150
151impl<T: Scalar> ExactSizeIterator for Values<'_, T> {}
152
153/// A flat byte buffer addressed by offset: the transport for Wasm linear
154/// memory, and for any caller whose pointers are offsets into one buffer.
155/// Offset 0 is null.
156pub struct LinearMemory<'a> {
157    bytes: &'a mut [u8],
158    word_bits: u32,
159}
160
161impl<'a> LinearMemory<'a> {
162    pub fn new(bytes: &'a mut [u8], word_bits: u32) -> Self {
163        assert!(word_bits == 32 || word_bits == 64);
164        assert!(
165            word_bits <= usize::BITS,
166            "a 64-bit guest needs a 64-bit host"
167        );
168        Self { bytes, word_bits }
169    }
170
171    fn range(&self, address: Word, length: usize) -> Result<core::ops::Range<usize>> {
172        if length != 0 && address == 0 {
173            return Err(Error::InvalidMemory);
174        }
175        let start = address;
176        let end = start.checked_add(length).ok_or(Error::InvalidMemory)?;
177        self.bytes.get(start..end).ok_or(Error::InvalidMemory)?;
178        Ok(start..end)
179    }
180}
181
182impl Transport for LinearMemory<'_> {
183    fn word_bits(&self) -> u32 {
184        self.word_bits
185    }
186
187    fn bytes(&self, address: Word, length: usize) -> Result<&[u8]> {
188        Ok(&self.bytes[self.range(address, length)?])
189    }
190
191    fn bytes_mut(&mut self, address: Word, length: usize) -> Result<&mut [u8]> {
192        let range = self.range(address, length)?;
193        Ok(&mut self.bytes[range])
194    }
195
196    fn c_string(&self, address: Word, limit: usize) -> Result<&CStr> {
197        let start = self.range(address, 1)?.start;
198        let window = &self.bytes[start..self.bytes.len().min(start.saturating_add(limit))];
199        match window.iter().position(|&byte| byte == 0) {
200            Some(end) => {
201                Ok(CStr::from_bytes_with_nul(&window[..=end]).expect("first NUL ends the string"))
202            }
203            // No NUL within the limit: too long if the window is full, else it ran off memory.
204            None if window.len() == limit => Err(Error::ResourceLimit),
205            None => Err(Error::InvalidMemory),
206        }
207    }
208}
209
210#[cfg(test)]
211mod tests {
212    use super::*;
213
214    #[test]
215    fn linear_memory_allows_null_only_for_empty_ranges_and_bounds_every_range() {
216        let mut bytes = [0; 8];
217        let memory = LinearMemory::new(&mut bytes, 32);
218        assert_eq!(memory.bytes(0, 0), Ok(&[][..]));
219        assert_eq!(memory.bytes(0, 1), Err(Error::InvalidMemory));
220        assert_eq!(memory.bytes(8, 0), Ok(&[][..]));
221        assert_eq!(memory.bytes(9, 0), Err(Error::InvalidMemory));
222        assert_eq!(memory.bytes(7, 2), Err(Error::InvalidMemory));
223        assert_eq!(memory.bytes(Word::MAX, 2), Err(Error::InvalidMemory));
224        assert_eq!(memory.c_string(0, 4), Err(Error::InvalidMemory));
225        assert_eq!(memory.c_string(8, 4), Err(Error::InvalidMemory));
226    }
227
228    #[test]
229    fn scalars_and_words_are_little_endian_at_unaligned_offsets() {
230        let mut bytes = [0; 24];
231        let mut memory = LinearMemory::new(&mut bytes, 32);
232        let transport: &mut dyn Transport = &mut memory;
233        transport.write(1, 0x1234_5678_u32).unwrap();
234        transport.write(5, -2_i32).unwrap();
235        transport.write(9, 0xabcd_u16).unwrap();
236        transport.put_word(11, 0x0102_0304);
237        assert_eq!(transport.read::<u32>(1), Ok(0x1234_5678));
238        assert_eq!(transport.read::<i32>(5), Ok(-2));
239        assert_eq!(transport.read_at::<u16>(9, 0), Ok(0xabcd));
240        assert_eq!(transport.read_word(11), Ok(0x0102_0304));
241        assert_eq!(transport.write(23, 0_u16), Err(Error::InvalidMemory));
242        assert_eq!(
243            transport.read_at::<u32>(1, usize::MAX / 4),
244            Err(Error::InvalidMemory)
245        );
246        assert_eq!(
247            &bytes[1..15],
248            &[
249                0x78, 0x56, 0x34, 0x12, 0xfe, 0xff, 0xff, 0xff, 0xcd, 0xab, 0x04, 0x03, 0x02, 0x01
250            ]
251        );
252    }
253
254    #[test]
255    fn values_decode_lazily_and_reject_overflowing_counts() {
256        let mut bytes = [0, 1, 0, 2, 0, 3, 0];
257        let memory = LinearMemory::new(&mut bytes, 32);
258        let transport: &dyn Transport = &memory;
259        let values = transport.values::<u16>(1, 3).unwrap();
260        assert_eq!(values.len(), 3);
261        assert!(values.eq([1, 2, 3]));
262        assert!(transport.values::<u16>(1, 4).is_err());
263        assert!(transport.values::<u32>(1, usize::MAX).is_err());
264        assert_eq!(transport.values::<u32>(0, 0).unwrap().count(), 0);
265    }
266
267    #[cfg(target_pointer_width = "64")]
268    #[test]
269    fn sixty_four_bit_words_use_the_full_host_word() {
270        let mut bytes = [0; 12];
271        let mut memory = LinearMemory::new(&mut bytes, 64);
272        let transport: &mut dyn Transport = &mut memory;
273        transport.put_word(3, 0x0102_0304_0506_0708);
274        assert_eq!(transport.read_word(3), Ok(0x0102_0304_0506_0708));
275        assert_eq!(transport.read_word(5), Err(Error::InvalidMemory));
276    }
277
278    #[test]
279    fn c_strings_borrow_guest_memory_in_place_up_to_the_end_of_memory() {
280        let mut bytes = *b"\0abc\0de";
281        let base = bytes.as_ptr() as usize;
282        let memory = LinearMemory::new(&mut bytes, 32);
283        let text = memory.c_string(1, 4).unwrap();
284        assert_eq!(text.to_bytes(), b"abc");
285        assert_eq!(text.as_ptr() as usize, base + 1);
286        assert_eq!(memory.c_string(1, 3), Err(Error::ResourceLimit));
287        // Runs off memory before the limit: invalid, not too long.
288        assert_eq!(memory.c_string(5, 8), Err(Error::InvalidMemory));
289        assert_eq!(memory.c_string(5, 2), Err(Error::ResourceLimit));
290    }
291}