wasmtime/runtime/
memory.rs

1use crate::Trap;
2use crate::prelude::*;
3use crate::runtime::vm::{self, ExportMemory, VMStore};
4use crate::store::{StoreInstanceId, StoreOpaque, StoreResourceLimiter};
5use crate::trampoline::generate_memory_export;
6use crate::{AsContext, AsContextMut, Engine, MemoryType, StoreContext, StoreContextMut};
7use core::cell::UnsafeCell;
8use core::fmt;
9use core::slice;
10use core::time::Duration;
11use wasmtime_environ::DefinedMemoryIndex;
12
13pub use crate::runtime::vm::WaitResult;
14
15/// Error for out of bounds [`Memory`] access.
16#[derive(Debug)]
17#[non_exhaustive]
18pub struct MemoryAccessError {
19    // Keep struct internals private for future extensibility.
20    _private: (),
21}
22
23impl fmt::Display for MemoryAccessError {
24    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
25        write!(f, "out of bounds memory access")
26    }
27}
28
29impl core::error::Error for MemoryAccessError {}
30
31/// A WebAssembly linear memory.
32///
33/// WebAssembly memories represent a contiguous array of bytes that have a size
34/// that is always a multiple of the WebAssembly page size, currently 64
35/// kilobytes.
36///
37/// WebAssembly memory is used for global data (not to be confused with wasm
38/// `global` items), statics in C/C++/Rust, shadow stack memory, etc. Accessing
39/// wasm memory is generally quite fast.
40///
41/// Memories, like other wasm items, are owned by a [`Store`](crate::Store).
42///
43/// # `Memory` and Safety
44///
45/// Linear memory is a lynchpin of safety for WebAssembly. In Wasmtime there are
46/// safe methods of interacting with a [`Memory`]:
47///
48/// * [`Memory::read`]
49/// * [`Memory::write`]
50/// * [`Memory::data`]
51/// * [`Memory::data_mut`]
52///
53/// Note that all of these consider the entire store context as borrowed for the
54/// duration of the call or the duration of the returned slice. This largely
55/// means that while the function is running you'll be unable to borrow anything
56/// else from the store. This includes getting access to the `T` on
57/// [`Store<T>`](crate::Store), but it also means that you can't recursively
58/// call into WebAssembly for instance.
59///
60/// If you'd like to dip your toes into handling [`Memory`] in a more raw
61/// fashion (e.g. by using raw pointers or raw slices), then there's a few
62/// important points to consider when doing so:
63///
64/// * Any recursive calls into WebAssembly can possibly modify any byte of the
65///   entire memory. This means that whenever wasm is called Rust can't have any
66///   long-lived borrows live across the wasm function call. Slices like `&mut
67///   [u8]` will be violated because they're not actually exclusive at that
68///   point, and slices like `&[u8]` are also violated because their contents
69///   may be mutated.
70///
71/// * WebAssembly memories can grow, and growth may change the base pointer.
72///   This means that even holding a raw pointer to memory over a wasm function
73///   call is also incorrect. Anywhere in the function call the base address of
74///   memory may change. Note that growth can also be requested from the
75///   embedding API as well.
76///
77/// As a general rule of thumb it's recommended to stick to the safe methods of
78/// [`Memory`] if you can. It's not advised to use raw pointers or `unsafe`
79/// operations because of how easy it is to accidentally get things wrong.
80///
81/// Some examples of safely interacting with memory are:
82///
83/// ```rust
84/// use wasmtime::{Memory, Store, MemoryAccessError};
85///
86/// // Memory can be read and written safely with the `Memory::read` and
87/// // `Memory::write` methods.
88/// // An error is returned if the copy did not succeed.
89/// fn safe_examples(mem: Memory, store: &mut Store<()>) -> Result<(), MemoryAccessError> {
90///     let offset = 5;
91///     mem.write(&mut *store, offset, b"hello")?;
92///     let mut buffer = [0u8; 5];
93///     mem.read(&store, offset, &mut buffer)?;
94///     assert_eq!(b"hello", &buffer);
95///
96///     // Note that while this is safe care must be taken because the indexing
97///     // here may panic if the memory isn't large enough.
98///     assert_eq!(&mem.data(&store)[offset..offset + 5], b"hello");
99///     mem.data_mut(&mut *store)[offset..offset + 5].copy_from_slice(b"bye!!");
100///
101///     Ok(())
102/// }
103/// ```
104///
105/// It's worth also, however, covering some examples of **incorrect**,
106/// **unsafe** usages of `Memory`. Do not do these things!
107///
108/// ```rust
109/// use wasmtime::{Memory, Result, Store};
110///
111/// // NOTE: All code in this function is not safe to execute and may cause
112/// // segfaults/undefined behavior at runtime. Do not copy/paste these examples
113/// // into production code!
114/// unsafe fn unsafe_examples(mem: Memory, store: &mut Store<()>) -> Result<()> {
115///     // First and foremost, any borrow can be invalidated at any time via the
116///     // `Memory::grow` function. This can relocate memory which causes any
117///     // previous pointer to be possibly invalid now.
118///     unsafe {
119///         let pointer: &u8 = &*mem.data_ptr(&store);
120///         mem.grow(&mut *store, 1)?; // invalidates `pointer`!
121///         // println!("{}", *pointer); // FATAL: use-after-free
122///     }
123///
124///     // Note that the use-after-free also applies to slices, whether they're
125///     // slices of bytes or strings.
126///     unsafe {
127///         let mem_slice = std::slice::from_raw_parts(
128///             mem.data_ptr(&store),
129///             mem.data_size(&store),
130///         );
131///         let slice: &[u8] = &mem_slice[0x100..0x102];
132///         mem.grow(&mut *store, 1)?; // invalidates `slice`!
133///         // println!("{:?}", slice); // FATAL: use-after-free
134///     }
135///
136///     // The `Memory` type may be stored in other locations, so if you hand
137///     // off access to the `Store` then those locations may also call
138///     // `Memory::grow` or similar, so it's not enough to just audit code for
139///     // calls to `Memory::grow`.
140///     unsafe {
141///         let pointer: &u8 = &*mem.data_ptr(&store);
142///         some_other_function(store); // may invalidate `pointer` through use of `store`
143///         // println!("{:?}", pointer); // FATAL: maybe a use-after-free
144///     }
145///
146///     // An especially subtle aspect of accessing a wasm instance's memory is
147///     // that you need to be extremely careful about aliasing. Anyone at any
148///     // time can call `data_unchecked()` or `data_unchecked_mut()`, which
149///     // means you can easily have aliasing mutable references:
150///     unsafe {
151///         let ref1: &u8 = &*mem.data_ptr(&store).add(0x100);
152///         let ref2: &mut u8 = &mut *mem.data_ptr(&store).add(0x100);
153///         // *ref2 = *ref1; // FATAL: violates Rust's aliasing rules
154///     }
155///
156///     Ok(())
157/// }
158/// # fn some_other_function(store: &mut Store<()>) {}
159/// ```
160///
161/// Overall there's some general rules of thumb when unsafely working with
162/// `Memory` and getting raw pointers inside of it:
163///
164/// * If you never have a "long lived" pointer into memory, you're likely in the
165///   clear. Care still needs to be taken in threaded scenarios or when/where
166///   data is read, but you'll be shielded from many classes of issues.
167/// * Long-lived pointers must always respect Rust'a aliasing rules. It's ok for
168///   shared borrows to overlap with each other, but mutable borrows must
169///   overlap with nothing.
170/// * Long-lived pointers are only valid if they're not invalidated for their
171///   lifetime. This means that [`Store`](crate::Store) isn't used to reenter
172///   wasm or the memory itself is never grown or otherwise modified/aliased.
173///
174/// At this point it's worth reiterating again that unsafely working with
175/// `Memory` is pretty tricky and not recommended! It's highly recommended to
176/// use the safe methods to interact with [`Memory`] whenever possible.
177///
178/// ## `Memory` Safety and Threads
179///
180/// Currently the `wasmtime` crate does not implement the wasm threads proposal,
181/// but it is planned to do so. It may be interesting to readers to see how this
182/// affects memory safety and what was previously just discussed as well.
183///
184/// Once threads are added into the mix, all of the above rules still apply.
185/// There's an additional consideration that all reads and writes can happen
186/// concurrently, though. This effectively means that any borrow into wasm
187/// memory are virtually never safe to have.
188///
189/// Mutable pointers are fundamentally unsafe to have in a concurrent scenario
190/// in the face of arbitrary wasm code. Only if you dynamically know for sure
191/// that wasm won't access a region would it be safe to construct a mutable
192/// pointer. Additionally even shared pointers are largely unsafe because their
193/// underlying contents may change, so unless `UnsafeCell` in one form or
194/// another is used everywhere there's no safety.
195///
196/// One important point about concurrency is that while [`Memory::grow`] can
197/// happen concurrently it will never relocate the base pointer. Shared
198/// memories must always have a maximum size and they will be preallocated such
199/// that growth will never relocate the base pointer. The current size of the
200/// memory may still change over time though.
201///
202/// Overall the general rule of thumb for shared memories is that you must
203/// atomically read and write everything. Nothing can be borrowed and everything
204/// must be eagerly copied out. This means that [`Memory::data`] and
205/// [`Memory::data_mut`] won't work in the future (they'll probably return an
206/// error) for shared memories when they're implemented. When possible it's
207/// recommended to use [`Memory::read`] and [`Memory::write`] which will still
208/// be provided.
209#[derive(Copy, Clone, Debug)]
210#[repr(C)] // here for the C API
211pub struct Memory {
212    /// The internal store instance that this memory belongs to.
213    instance: StoreInstanceId,
214    /// The index of the memory, within `instance` above, that this memory
215    /// refers to.
216    index: DefinedMemoryIndex,
217}
218
219// Double-check that the C representation in `extern.h` matches our in-Rust
220// representation here in terms of size/alignment/etc.
221const _: () = {
222    #[repr(C)]
223    struct Tmp(u64, u32);
224    #[repr(C)]
225    struct C(Tmp, u32);
226    assert!(core::mem::size_of::<C>() == core::mem::size_of::<Memory>());
227    assert!(core::mem::align_of::<C>() == core::mem::align_of::<Memory>());
228    assert!(core::mem::offset_of!(Memory, instance) == 0);
229};
230
231impl Memory {
232    /// Creates a new WebAssembly memory given the configuration of `ty`.
233    ///
234    /// The `store` argument will be the owner of the returned [`Memory`]. All
235    /// WebAssembly memory is initialized to zero.
236    ///
237    /// # Panics
238    ///
239    /// This function will panic if the [`Store`](`crate::Store`) has a
240    /// [`ResourceLimiterAsync`](`crate::ResourceLimiterAsync`) (see also:
241    /// [`Store::limiter_async`](`crate::Store::limiter_async`)). When
242    /// using an async resource limiter, use [`Memory::new_async`] instead.
243    ///
244    /// # Examples
245    ///
246    /// ```
247    /// # use wasmtime::*;
248    /// # fn main() -> Result<()> {
249    /// let engine = Engine::default();
250    /// let mut store = Store::new(&engine, ());
251    ///
252    /// let memory_ty = MemoryType::new(1, None);
253    /// let memory = Memory::new(&mut store, memory_ty)?;
254    ///
255    /// let module = Module::new(&engine, "(module (memory (import \"\" \"\") 1))")?;
256    /// let instance = Instance::new(&mut store, &module, &[memory.into()])?;
257    /// // ...
258    /// # Ok(())
259    /// # }
260    /// ```
261    pub fn new(mut store: impl AsContextMut, ty: MemoryType) -> Result<Memory> {
262        let (mut limiter, store) = store.as_context_mut().0.resource_limiter_and_store_opaque();
263        vm::one_poll(Self::_new(store, limiter.as_mut(), ty))
264            .expect("must use `new_async` when async resource limiters are in use")
265    }
266
267    /// Async variant of [`Memory::new`]. You must use this variant with
268    /// [`Store`](`crate::Store`)s which have a
269    /// [`ResourceLimiterAsync`](`crate::ResourceLimiterAsync`).
270    ///
271    /// # Panics
272    ///
273    /// This function will panic when used with a non-async
274    /// [`Store`](`crate::Store`).
275    #[cfg(feature = "async")]
276    pub async fn new_async(mut store: impl AsContextMut, ty: MemoryType) -> Result<Memory> {
277        let (mut limiter, store) = store.as_context_mut().0.resource_limiter_and_store_opaque();
278        Self::_new(store, limiter.as_mut(), ty).await
279    }
280
281    /// Helper function for attaching the memory to a "frankenstein" instance
282    async fn _new(
283        store: &mut StoreOpaque,
284        limiter: Option<&mut StoreResourceLimiter<'_>>,
285        ty: MemoryType,
286    ) -> Result<Memory> {
287        if ty.is_shared() {
288            bail!("shared memories must be created through `SharedMemory`")
289        }
290        Ok(generate_memory_export(store, limiter, &ty, None)
291            .await?
292            .unshared()
293            .unwrap())
294    }
295
296    /// Returns the underlying type of this memory.
297    ///
298    /// # Panics
299    ///
300    /// Panics if this memory doesn't belong to `store`.
301    ///
302    /// # Examples
303    ///
304    /// ```
305    /// # use wasmtime::*;
306    /// # fn main() -> Result<()> {
307    /// let engine = Engine::default();
308    /// let mut store = Store::new(&engine, ());
309    /// let module = Module::new(&engine, "(module (memory (export \"mem\") 1))")?;
310    /// let instance = Instance::new(&mut store, &module, &[])?;
311    /// let memory = instance.get_memory(&mut store, "mem").unwrap();
312    /// let ty = memory.ty(&store);
313    /// assert_eq!(ty.minimum(), 1);
314    /// # Ok(())
315    /// # }
316    /// ```
317    pub fn ty(&self, store: impl AsContext) -> MemoryType {
318        let store = store.as_context();
319        MemoryType::from_wasmtime_memory(self.wasmtime_ty(store.0))
320    }
321
322    /// Safely reads memory contents at the given offset into a buffer.
323    ///
324    /// The entire buffer will be filled.
325    ///
326    /// If `offset + buffer.len()` exceed the current memory capacity, then the
327    /// buffer is left untouched and a [`MemoryAccessError`] is returned.
328    ///
329    /// # Panics
330    ///
331    /// Panics if this memory doesn't belong to `store`.
332    pub fn read(
333        &self,
334        store: impl AsContext,
335        offset: usize,
336        buffer: &mut [u8],
337    ) -> Result<(), MemoryAccessError> {
338        let store = store.as_context();
339        let slice = self
340            .data(&store)
341            .get(offset..)
342            .and_then(|s| s.get(..buffer.len()))
343            .ok_or(MemoryAccessError { _private: () })?;
344        buffer.copy_from_slice(slice);
345        Ok(())
346    }
347
348    /// Safely writes contents of a buffer to this memory at the given offset.
349    ///
350    /// If the `offset + buffer.len()` exceeds the current memory capacity, then
351    /// none of the buffer is written to memory and a [`MemoryAccessError`] is
352    /// returned.
353    ///
354    /// # Panics
355    ///
356    /// Panics if this memory doesn't belong to `store`.
357    pub fn write(
358        &self,
359        mut store: impl AsContextMut,
360        offset: usize,
361        buffer: &[u8],
362    ) -> Result<(), MemoryAccessError> {
363        let mut context = store.as_context_mut();
364        self.data_mut(&mut context)
365            .get_mut(offset..)
366            .and_then(|s| s.get_mut(..buffer.len()))
367            .ok_or(MemoryAccessError { _private: () })?
368            .copy_from_slice(buffer);
369        Ok(())
370    }
371
372    /// Returns this memory as a native Rust slice.
373    ///
374    /// Note that this method will consider the entire store context provided as
375    /// borrowed for the duration of the lifetime of the returned slice.
376    ///
377    /// # Panics
378    ///
379    /// Panics if this memory doesn't belong to `store`.
380    pub fn data<'a, T: 'static>(&self, store: impl Into<StoreContext<'a, T>>) -> &'a [u8] {
381        unsafe {
382            let store = store.into();
383            let definition = store[self.instance].memory(self.index);
384            debug_assert!(!self.ty(store).is_shared());
385            slice::from_raw_parts(definition.base.as_ptr(), definition.current_length())
386        }
387    }
388
389    /// Returns this memory as a native Rust mutable slice.
390    ///
391    /// Note that this method will consider the entire store context provided as
392    /// borrowed for the duration of the lifetime of the returned slice.
393    ///
394    /// # Panics
395    ///
396    /// Panics if this memory doesn't belong to `store`.
397    pub fn data_mut<'a, T: 'static>(
398        &self,
399        store: impl Into<StoreContextMut<'a, T>>,
400    ) -> &'a mut [u8] {
401        unsafe {
402            let store = store.into();
403            let definition = store[self.instance].memory(self.index);
404            debug_assert!(!self.ty(store).is_shared());
405            slice::from_raw_parts_mut(definition.base.as_ptr(), definition.current_length())
406        }
407    }
408
409    /// Same as [`Memory::data_mut`], but also returns the `T` from the
410    /// [`StoreContextMut`].
411    ///
412    /// This method can be used when you want to simultaneously work with the
413    /// `T` in the store as well as the memory behind this [`Memory`]. Using
414    /// [`Memory::data_mut`] would consider the entire store borrowed, whereas
415    /// this method allows the Rust compiler to see that the borrow of this
416    /// memory and the borrow of `T` are disjoint.
417    ///
418    /// # Panics
419    ///
420    /// Panics if this memory doesn't belong to `store`.
421    pub fn data_and_store_mut<'a, T: 'static>(
422        &self,
423        store: impl Into<StoreContextMut<'a, T>>,
424    ) -> (&'a mut [u8], &'a mut T) {
425        // Note the unsafety here. Our goal is to simultaneously borrow the
426        // memory and custom data from `store`, and the store it's connected
427        // to. Rust will not let us do that, however, because we must call two
428        // separate methods (both of which borrow the whole `store`) and one of
429        // our borrows is mutable (the custom data).
430        //
431        // This operation, however, is safe because these borrows do not overlap
432        // and in the process of borrowing them mutability doesn't actually
433        // touch anything. This is akin to mutably borrowing two indices in an
434        // array, which is safe so long as the indices are separate.
435        unsafe {
436            let mut store = store.into();
437            let data = &mut *(store.data_mut() as *mut T);
438            (self.data_mut(store), data)
439        }
440    }
441
442    /// Returns the base pointer, in the host's address space, that the memory
443    /// is located at.
444    ///
445    /// For more information and examples see the documentation on the
446    /// [`Memory`] type.
447    ///
448    /// # Panics
449    ///
450    /// Panics if this memory doesn't belong to `store`.
451    pub fn data_ptr(&self, store: impl AsContext) -> *mut u8 {
452        store.as_context()[self.instance]
453            .memory(self.index)
454            .base
455            .as_ptr()
456    }
457
458    /// Returns the byte length of this memory.
459    ///
460    /// WebAssembly memories are made up of a whole number of pages, so the byte
461    /// size returned will always be a multiple of this memory's page size. Note
462    /// that different Wasm memories may have different page sizes. You can get
463    /// a memory's page size via the [`Memory::page_size`] method.
464    ///
465    /// By default the page size is 64KiB (aka `0x10000`, `2**16`, `1<<16`, or
466    /// `65536`) but [the custom-page-sizes proposal] allows a memory to opt
467    /// into a page size of `1`. Future extensions might allow any power of two
468    /// as a page size.
469    ///
470    /// [the custom-page-sizes proposal]: https://github.com/WebAssembly/custom-page-sizes
471    ///
472    /// For more information and examples see the documentation on the
473    /// [`Memory`] type.
474    ///
475    /// # Panics
476    ///
477    /// Panics if this memory doesn't belong to `store`.
478    pub fn data_size(&self, store: impl AsContext) -> usize {
479        self.internal_data_size(store.as_context().0)
480    }
481
482    pub(crate) fn internal_data_size(&self, store: &StoreOpaque) -> usize {
483        store[self.instance].memory(self.index).current_length()
484    }
485
486    /// Returns the size, in units of pages, of this Wasm memory.
487    ///
488    /// WebAssembly memories are made up of a whole number of pages, so the byte
489    /// size returned will always be a multiple of this memory's page size. Note
490    /// that different Wasm memories may have different page sizes. You can get
491    /// a memory's page size via the [`Memory::page_size`] method.
492    ///
493    /// By default the page size is 64KiB (aka `0x10000`, `2**16`, `1<<16`, or
494    /// `65536`) but [the custom-page-sizes proposal] allows a memory to opt
495    /// into a page size of `1`. Future extensions might allow any power of two
496    /// as a page size.
497    ///
498    /// [the custom-page-sizes proposal]: https://github.com/WebAssembly/custom-page-sizes
499    ///
500    /// # Panics
501    ///
502    /// Panics if this memory doesn't belong to `store`.
503    pub fn size(&self, store: impl AsContext) -> u64 {
504        self.internal_size(store.as_context().0)
505    }
506
507    pub(crate) fn internal_size(&self, store: &StoreOpaque) -> u64 {
508        let byte_size = self.internal_data_size(store);
509        let page_size = usize::try_from(self._page_size(store)).unwrap();
510        u64::try_from(byte_size / page_size).unwrap()
511    }
512
513    /// Returns the size of a page, in bytes, for this memory.
514    ///
515    /// WebAssembly memories are made up of a whole number of pages, so the byte
516    /// size (as returned by [`Memory::data_size`]) will always be a multiple of
517    /// their page size. Different Wasm memories may have different page sizes.
518    ///
519    /// By default this is 64KiB (aka `0x10000`, `2**16`, `1<<16`, or `65536`)
520    /// but [the custom-page-sizes proposal] allows opting into a page size of
521    /// `1`. Future extensions might allow any power of two as a page size.
522    ///
523    /// [the custom-page-sizes proposal]: https://github.com/WebAssembly/custom-page-sizes
524    pub fn page_size(&self, store: impl AsContext) -> u64 {
525        self._page_size(store.as_context().0)
526    }
527
528    pub(crate) fn _page_size(&self, store: &StoreOpaque) -> u64 {
529        self.wasmtime_ty(store).page_size()
530    }
531
532    /// Returns the log2 of this memory's page size, in bytes.
533    ///
534    /// WebAssembly memories are made up of a whole number of pages, so the byte
535    /// size (as returned by [`Memory::data_size`]) will always be a multiple of
536    /// their page size. Different Wasm memories may have different page sizes.
537    ///
538    /// By default the page size is 64KiB (aka `0x10000`, `2**16`, `1<<16`, or
539    /// `65536`) but [the custom-page-sizes proposal] allows opting into a page
540    /// size of `1`. Future extensions might allow any power of two as a page
541    /// size.
542    ///
543    /// [the custom-page-sizes proposal]: https://github.com/WebAssembly/custom-page-sizes
544    pub fn page_size_log2(&self, store: impl AsContext) -> u8 {
545        self._page_size_log2(store.as_context().0)
546    }
547
548    pub(crate) fn _page_size_log2(&self, store: &StoreOpaque) -> u8 {
549        self.wasmtime_ty(store).page_size_log2
550    }
551
552    /// Grows this WebAssembly memory by `delta` pages.
553    ///
554    /// This will attempt to add `delta` more pages of memory on to the end of
555    /// this `Memory` instance. If successful this may relocate the memory and
556    /// cause [`Memory::data_ptr`] to return a new value. Additionally any
557    /// unsafely constructed slices into this memory may no longer be valid.
558    ///
559    /// On success returns the number of pages this memory previously had
560    /// before the growth succeeded.
561    ///
562    /// Note that, by default, a WebAssembly memory's page size is 64KiB (aka
563    /// 65536 or 2<sup>16</sup>). The [custom-page-sizes proposal] allows Wasm
564    /// memories to opt into a page size of one byte (and this may be further
565    /// relaxed to any power of two in a future extension).
566    ///
567    /// [custom-page-sizes proposal]: https://github.com/WebAssembly/custom-page-sizes
568    ///
569    /// # Errors
570    ///
571    /// Returns an error if memory could not be grown, for example if it exceeds
572    /// the maximum limits of this memory. A
573    /// [`ResourceLimiter`](crate::ResourceLimiter) is another example of
574    /// preventing a memory to grow.
575    ///
576    /// # Panics
577    ///
578    /// Panics if this memory doesn't belong to `store`.
579    ///
580    /// This function will panic if the [`Store`](`crate::Store`) has a
581    /// [`ResourceLimiterAsync`](`crate::ResourceLimiterAsync`) (see also:
582    /// [`Store::limiter_async`](`crate::Store::limiter_async`). When using an
583    /// async resource limiter, use [`Memory::grow_async`] instead.
584    ///
585    /// # Examples
586    ///
587    /// ```
588    /// # use wasmtime::*;
589    /// # fn main() -> Result<()> {
590    /// let engine = Engine::default();
591    /// let mut store = Store::new(&engine, ());
592    /// let module = Module::new(&engine, "(module (memory (export \"mem\") 1 2))")?;
593    /// let instance = Instance::new(&mut store, &module, &[])?;
594    /// let memory = instance.get_memory(&mut store, "mem").unwrap();
595    ///
596    /// assert_eq!(memory.size(&store), 1);
597    /// assert_eq!(memory.grow(&mut store, 1)?, 1);
598    /// assert_eq!(memory.size(&store), 2);
599    /// assert!(memory.grow(&mut store, 1).is_err());
600    /// assert_eq!(memory.size(&store), 2);
601    /// assert_eq!(memory.grow(&mut store, 0)?, 2);
602    /// # Ok(())
603    /// # }
604    /// ```
605    pub fn grow(&self, mut store: impl AsContextMut, delta: u64) -> Result<u64> {
606        let store = store.as_context_mut().0;
607        let (mut limiter, store) = store.resource_limiter_and_store_opaque();
608        vm::one_poll(self._grow(store, limiter.as_mut(), delta))
609            .expect("must use `grow_async` if an async resource limiter is used")
610    }
611
612    /// Async variant of [`Memory::grow`]. Required when using a
613    /// [`ResourceLimiterAsync`](`crate::ResourceLimiterAsync`).
614    ///
615    /// # Panics
616    ///
617    /// This function will panic when used with a non-async
618    /// [`Store`](`crate::Store`).
619    #[cfg(feature = "async")]
620    pub async fn grow_async(&self, mut store: impl AsContextMut, delta: u64) -> Result<u64> {
621        let store = store.as_context_mut();
622        let (mut limiter, store) = store.0.resource_limiter_and_store_opaque();
623        self._grow(store, limiter.as_mut(), delta).await
624    }
625
626    async fn _grow(
627        &self,
628        store: &mut StoreOpaque,
629        limiter: Option<&mut StoreResourceLimiter<'_>>,
630        delta: u64,
631    ) -> Result<u64> {
632        let result = self
633            .instance
634            .get_mut(store)
635            .memory_grow(limiter, self.index, delta)
636            .await?;
637        match result {
638            Some(size) => {
639                let page_size = self.wasmtime_ty(store).page_size();
640                Ok(u64::try_from(size).unwrap() / page_size)
641            }
642            None => bail!("failed to grow memory by `{delta}`"),
643        }
644    }
645
646    /// Creates a new memory from its raw component parts.
647    ///
648    /// # Safety
649    ///
650    /// The caller must ensure that the memory pointed to by `instance` and
651    /// `index` is not a shared memory. For that `SharedMemory` must be used
652    /// instead.
653    pub(crate) unsafe fn from_raw(instance: StoreInstanceId, index: DefinedMemoryIndex) -> Memory {
654        Memory { instance, index }
655    }
656
657    pub(crate) fn wasmtime_ty<'a>(&self, store: &'a StoreOpaque) -> &'a wasmtime_environ::Memory {
658        let module = store[self.instance].env_module();
659        let index = module.memory_index(self.index);
660        &module.memories[index]
661    }
662
663    pub(crate) fn vmimport(&self, store: &StoreOpaque) -> crate::runtime::vm::VMMemoryImport {
664        store[self.instance].get_defined_memory_vmimport(self.index)
665    }
666
667    pub(crate) fn comes_from_same_store(&self, store: &StoreOpaque) -> bool {
668        store.id() == self.instance.store_id()
669    }
670
671    /// Get a stable hash key for this memory.
672    ///
673    /// Even if the same underlying memory definition is added to the
674    /// `StoreData` multiple times and becomes multiple `wasmtime::Memory`s,
675    /// this hash key will be consistent across all of these memories.
676    #[cfg(feature = "coredump")]
677    pub(crate) fn hash_key(&self, store: &StoreOpaque) -> impl core::hash::Hash + Eq + use<> {
678        store[self.instance].memory_ptr(self.index).as_ptr().addr()
679    }
680}
681
682/// A linear memory. This trait provides an interface for raw memory buffers
683/// which are used by wasmtime, e.g. inside ['Memory']. Such buffers are in
684/// principle not thread safe. By implementing this trait together with
685/// MemoryCreator, one can supply wasmtime with custom allocated host managed
686/// memory.
687///
688/// # Safety
689///
690/// The memory should be page aligned and a multiple of page size.
691/// To prevent possible silent overflows, the memory should be protected by a
692/// guard page.  Additionally the safety concerns explained in ['Memory'], for
693/// accessing the memory apply here as well.
694///
695/// Note that this is a relatively advanced feature and it is recommended to be
696/// familiar with wasmtime runtime code to use it.
697pub unsafe trait LinearMemory: Send + Sync + 'static {
698    /// Returns the number of allocated bytes which are accessible at this time.
699    fn byte_size(&self) -> usize;
700
701    /// Returns byte capacity of this linear memory's current allocation.
702    ///
703    /// Growth up to this value should not relocate the linear memory base
704    /// pointer.
705    fn byte_capacity(&self) -> usize;
706
707    /// Grows this memory to have the `new_size`, in bytes, specified.
708    ///
709    /// Returns `Err` if memory can't be grown by the specified amount
710    /// of bytes. The error may be downcastable to `std::io::Error`.
711    /// Returns `Ok` if memory was grown successfully.
712    fn grow_to(&mut self, new_size: usize) -> Result<()>;
713
714    /// Return the allocated memory as a mutable pointer to u8.
715    fn as_ptr(&self) -> *mut u8;
716}
717
718/// A memory creator. Can be used to provide a memory creator
719/// to wasmtime which supplies host managed memory.
720///
721/// # Safety
722///
723/// This trait is unsafe, as the memory safety depends on proper implementation
724/// of memory management. Memories created by the MemoryCreator should always be
725/// treated as owned by wasmtime instance, and any modification of them outside
726/// of wasmtime invoked routines is unsafe and may lead to corruption.
727///
728/// Note that this is a relatively advanced feature and it is recommended to be
729/// familiar with Wasmtime runtime code to use it.
730pub unsafe trait MemoryCreator: Send + Sync {
731    /// Create a new `LinearMemory` object from the specified parameters.
732    ///
733    /// The type of memory being created is specified by `ty` which indicates
734    /// both the minimum and maximum size, in wasm pages. The minimum and
735    /// maximum sizes, in bytes, are also specified as parameters to avoid
736    /// integer conversion if desired.
737    ///
738    /// The `reserved_size_in_bytes` value indicates the expected size of the
739    /// reservation that is to be made for this memory. If this value is `None`
740    /// than the implementation is free to allocate memory as it sees fit. If
741    /// the value is `Some`, however, then the implementation is expected to
742    /// reserve that many bytes for the memory's allocation, plus the guard
743    /// size at the end. Note that this reservation need only be a virtual
744    /// memory reservation, physical memory does not need to be allocated
745    /// immediately. In this case `grow` should never move the base pointer and
746    /// the maximum size of `ty` is guaranteed to fit within
747    /// `reserved_size_in_bytes`.
748    ///
749    /// The `guard_size_in_bytes` parameter indicates how many bytes of space,
750    /// after the memory allocation, is expected to be unmapped. JIT code will
751    /// elide bounds checks based on the `guard_size_in_bytes` provided, so for
752    /// JIT code to work correctly the memory returned will need to be properly
753    /// guarded with `guard_size_in_bytes` bytes left unmapped after the base
754    /// allocation.
755    ///
756    /// Note that the `reserved_size_in_bytes` and `guard_size_in_bytes` options
757    /// are tuned from the various [`Config`](crate::Config) methods about
758    /// memory sizes/guards. Additionally these two values are guaranteed to be
759    /// multiples of the system page size.
760    ///
761    /// Memory created from this method should be zero filled.
762    fn new_memory(
763        &self,
764        ty: MemoryType,
765        minimum: usize,
766        maximum: Option<usize>,
767        reserved_size_in_bytes: Option<usize>,
768        guard_size_in_bytes: usize,
769    ) -> Result<Box<dyn LinearMemory>, String>;
770}
771
772/// A constructor for externally-created shared memory.
773///
774/// The [threads proposal] adds the concept of "shared memory" to WebAssembly.
775/// This is much the same as a Wasm linear memory (i.e., [`Memory`]), but can be
776/// used concurrently by multiple agents. Because these agents may execute in
777/// different threads, [`SharedMemory`] must be thread-safe.
778///
779/// When the [threads proposal is enabled](crate::Config::wasm_threads) and the
780/// [the creation of shared memories is enabled](crate::Config::shared_memory),
781/// there are multiple ways to construct shared memory:
782///  1. for imported shared memory, e.g., `(import "env" "memory" (memory 1 1
783///     shared))`, the user must supply a [`SharedMemory`] with the
784///     externally-created memory as an import to the instance--e.g.,
785///     `shared_memory.into()`.
786///  2. for private or exported shared memory, e.g., `(export "env" "memory"
787///     (memory 1 1 shared))`, Wasmtime will create the memory internally during
788///     instantiation--access using `Instance::get_shared_memory()`.
789///
790/// [threads proposal]:
791///     https://github.com/WebAssembly/threads/blob/master/proposals/threads/Overview.md
792///
793/// # Examples
794///
795/// ```
796/// # use wasmtime::*;
797/// # fn main() -> Result<()> {
798/// let mut config = Config::new();
799/// config.wasm_threads(true);
800/// config.shared_memory(true);
801/// # if Engine::new(&config).is_err() { return Ok(()); }
802/// let engine = Engine::new(&config)?;
803/// let mut store = Store::new(&engine, ());
804///
805/// let shared_memory = SharedMemory::new(&engine, MemoryType::shared(1, 2))?;
806/// let module = Module::new(&engine, r#"(module (memory (import "" "") 1 2 shared))"#)?;
807/// let instance = Instance::new(&mut store, &module, &[shared_memory.into()])?;
808/// // ...
809/// # Ok(())
810/// # }
811/// ```
812#[derive(Clone)]
813pub struct SharedMemory {
814    vm: crate::runtime::vm::SharedMemory,
815    engine: Engine,
816}
817
818impl SharedMemory {
819    /// Construct a [`SharedMemory`] by providing both the `minimum` and
820    /// `maximum` number of 64K-sized pages. This call allocates the necessary
821    /// pages on the system.
822    #[cfg(feature = "threads")]
823    pub fn new(engine: &Engine, ty: MemoryType) -> Result<Self> {
824        if !ty.is_shared() {
825            bail!("shared memory must have the `shared` flag enabled on its memory type")
826        }
827        debug_assert!(ty.maximum().is_some());
828
829        let ty = ty.wasmtime_memory();
830        let memory = crate::runtime::vm::SharedMemory::new(engine, ty)?;
831
832        Ok(Self {
833            vm: memory,
834            engine: engine.clone(),
835        })
836    }
837
838    /// Return the type of the shared memory.
839    pub fn ty(&self) -> MemoryType {
840        MemoryType::from_wasmtime_memory(&self.vm.ty())
841    }
842
843    /// Returns the size, in WebAssembly pages, of this wasm memory.
844    pub fn size(&self) -> u64 {
845        let byte_size = u64::try_from(self.data_size()).unwrap();
846        let page_size = self.page_size();
847        byte_size / page_size
848    }
849
850    /// Returns the size of a page, in bytes, for this memory.
851    ///
852    /// By default this is 64KiB (aka `0x10000`, `2**16`, `1<<16`, or `65536`)
853    /// but [the custom-page-sizes proposal] allows opting into a page size of
854    /// `1`. Future extensions might allow any power of two as a page size.
855    ///
856    /// [the custom-page-sizes proposal]: https://github.com/WebAssembly/custom-page-sizes
857    pub fn page_size(&self) -> u64 {
858        self.ty().page_size()
859    }
860
861    /// Returns the byte length of this memory.
862    ///
863    /// The returned value will be a multiple of the wasm page size, 64k.
864    ///
865    /// For more information and examples see the documentation on the
866    /// [`Memory`] type.
867    pub fn data_size(&self) -> usize {
868        self.vm.byte_size()
869    }
870
871    /// Return access to the available portion of the shared memory.
872    ///
873    /// The slice returned represents the region of accessible memory at the
874    /// time that this function was called. The contents of the returned slice
875    /// will reflect concurrent modifications happening on other threads.
876    ///
877    /// # Safety
878    ///
879    /// The returned slice is valid for the entire duration of the lifetime of
880    /// this instance of [`SharedMemory`]. The base pointer of a shared memory
881    /// does not change. This [`SharedMemory`] may grow further after this
882    /// function has been called, but the slice returned will not grow.
883    ///
884    /// Concurrent modifications may be happening to the data returned on other
885    /// threads. The `UnsafeCell<u8>` represents that safe access to the
886    /// contents of the slice is not possible through normal loads and stores.
887    ///
888    /// The memory returned must be accessed safely through the `Atomic*` types
889    /// in the [`std::sync::atomic`] module. Casting to those types must
890    /// currently be done unsafely.
891    pub fn data(&self) -> &[UnsafeCell<u8>] {
892        unsafe {
893            let definition = self.vm.vmmemory_ptr().as_ref();
894            slice::from_raw_parts(definition.base.as_ptr().cast(), definition.current_length())
895        }
896    }
897
898    /// Grows this WebAssembly memory by `delta` pages.
899    ///
900    /// This will attempt to add `delta` more pages of memory on to the end of
901    /// this `Memory` instance. If successful this may relocate the memory and
902    /// cause [`Memory::data_ptr`] to return a new value. Additionally any
903    /// unsafely constructed slices into this memory may no longer be valid.
904    ///
905    /// On success returns the number of pages this memory previously had
906    /// before the growth succeeded.
907    ///
908    /// # Errors
909    ///
910    /// Returns an error if memory could not be grown, for example if it exceeds
911    /// the maximum limits of this memory. A
912    /// [`ResourceLimiter`](crate::ResourceLimiter) is another example of
913    /// preventing a memory to grow.
914    pub fn grow(&self, delta: u64) -> Result<u64> {
915        match self.vm.grow(delta)? {
916            Some((old_size, _new_size)) => {
917                // For shared memory, the `VMMemoryDefinition` is updated inside
918                // the locked region.
919                Ok(u64::try_from(old_size).unwrap() / self.page_size())
920            }
921            None => bail!("failed to grow memory by `{delta}`"),
922        }
923    }
924
925    /// Equivalent of the WebAssembly `memory.atomic.notify` instruction for
926    /// this shared memory.
927    ///
928    /// This method allows embedders to notify threads blocked on the specified
929    /// `addr`, an index into wasm linear memory. Threads could include
930    /// wasm threads blocked on a `memory.atomic.wait*` instruction or embedder
931    /// threads blocked on [`SharedMemory::atomic_wait32`], for example.
932    ///
933    /// The `count` argument is the number of threads to wake up.
934    ///
935    /// This function returns the number of threads awoken.
936    ///
937    /// # Errors
938    ///
939    /// This function will return an error if `addr` is not within bounds or
940    /// not aligned to a 4-byte boundary.
941    pub fn atomic_notify(&self, addr: u64, count: u32) -> Result<u32, Trap> {
942        self.vm.atomic_notify(addr, count)
943    }
944
945    /// Equivalent of the WebAssembly `memory.atomic.wait32` instruction for
946    /// this shared memory.
947    ///
948    /// This method allows embedders to block the current thread until notified
949    /// via the `memory.atomic.notify` instruction or the
950    /// [`SharedMemory::atomic_notify`] method, enabling synchronization with
951    /// the wasm guest as desired.
952    ///
953    /// The `expected` argument is the expected 32-bit value to be stored at
954    /// the byte address `addr` specified. The `addr` specified is an index
955    /// into this linear memory.
956    ///
957    /// The optional `timeout` argument is the maximum amount of time to block
958    /// the current thread. If not specified the thread may sleep indefinitely.
959    ///
960    /// This function returns one of three possible values:
961    ///
962    /// * `WaitResult::Ok` - this function, loaded the value at `addr`, found
963    ///   it was equal to `expected`, and then blocked (all as one atomic
964    ///   operation). The thread was then awoken with a `memory.atomic.notify`
965    ///   instruction or the [`SharedMemory::atomic_notify`] method.
966    /// * `WaitResult::Mismatch` - the value at `addr` was loaded but was not
967    ///   equal to `expected` so the thread did not block and immediately
968    ///   returned.
969    /// * `WaitResult::TimedOut` - all the steps of `Ok` happened, except this
970    ///   thread was woken up due to a timeout.
971    ///
972    /// This function will not return due to spurious wakeups.
973    ///
974    /// # Errors
975    ///
976    /// This function will return an error if `addr` is not within bounds or
977    /// not aligned to a 4-byte boundary.
978    pub fn atomic_wait32(
979        &self,
980        addr: u64,
981        expected: u32,
982        timeout: Option<Duration>,
983    ) -> Result<WaitResult, Trap> {
984        self.vm.atomic_wait32(addr, expected, timeout)
985    }
986
987    /// Equivalent of the WebAssembly `memory.atomic.wait64` instruction for
988    /// this shared memory.
989    ///
990    /// For more information see [`SharedMemory::atomic_wait32`].
991    ///
992    /// # Errors
993    ///
994    /// Returns the same error as [`SharedMemory::atomic_wait32`] except that
995    /// the specified address must be 8-byte aligned instead of 4-byte aligned.
996    pub fn atomic_wait64(
997        &self,
998        addr: u64,
999        expected: u64,
1000        timeout: Option<Duration>,
1001    ) -> Result<WaitResult, Trap> {
1002        self.vm.atomic_wait64(addr, expected, timeout)
1003    }
1004
1005    /// Return a reference to the [`Engine`] used to configure the shared
1006    /// memory.
1007    pub(crate) fn engine(&self) -> &Engine {
1008        &self.engine
1009    }
1010
1011    /// Construct a single-memory instance to provide a way to import
1012    /// [`SharedMemory`] into other modules.
1013    pub(crate) fn vmimport(&self, store: &mut StoreOpaque) -> crate::runtime::vm::VMMemoryImport {
1014        // Note `vm::assert_ready` shouldn't panic here because this isn't
1015        // actually allocating any new memory (also no limiter), so resource
1016        // limiting shouldn't kick in.
1017        let memory = vm::assert_ready(generate_memory_export(
1018            store,
1019            None,
1020            &self.ty(),
1021            Some(&self.vm),
1022        ))
1023        .unwrap();
1024        match memory {
1025            ExportMemory::Unshared(_) => unreachable!(),
1026            ExportMemory::Shared(_shared, vmimport) => vmimport,
1027        }
1028    }
1029
1030    /// Creates a [`SharedMemory`] from its constituent parts.
1031    pub(crate) fn from_raw(vm: crate::runtime::vm::SharedMemory, engine: Engine) -> Self {
1032        SharedMemory { vm, engine }
1033    }
1034}
1035
1036impl fmt::Debug for SharedMemory {
1037    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1038        f.debug_struct("SharedMemory").finish_non_exhaustive()
1039    }
1040}
1041
1042#[cfg(test)]
1043mod tests {
1044    use crate::*;
1045
1046    // Assert that creating a memory via `Memory::new` respects the limits/tunables
1047    // in `Config`.
1048    #[test]
1049    fn respect_tunables() {
1050        let mut cfg = Config::new();
1051        cfg.memory_reservation(0).memory_guard_size(0);
1052        let mut store = Store::new(&Engine::new(&cfg).unwrap(), ());
1053        let ty = MemoryType::new(1, None);
1054        let mem = Memory::new(&mut store, ty).unwrap();
1055        let store = store.as_context();
1056        let tunables = store.engine().tunables();
1057        assert_eq!(tunables.memory_guard_size, 0);
1058        assert!(
1059            !mem.wasmtime_ty(store.0)
1060                .can_elide_bounds_check(tunables, 12)
1061        );
1062    }
1063
1064    #[test]
1065    fn hash_key_is_stable_across_duplicate_store_data_entries() -> Result<()> {
1066        let mut store = Store::<()>::default();
1067        let module = Module::new(
1068            store.engine(),
1069            r#"
1070                (module
1071                    (memory (export "m") 1 1)
1072                )
1073            "#,
1074        )?;
1075        let instance = Instance::new(&mut store, &module, &[])?;
1076
1077        // Each time we `get_memory`, we call `Memory::from_wasmtime` which adds
1078        // a new entry to `StoreData`, so `g1` and `g2` will have different
1079        // indices into `StoreData`.
1080        let m1 = instance.get_memory(&mut store, "m").unwrap();
1081        let m2 = instance.get_memory(&mut store, "m").unwrap();
1082
1083        // That said, they really point to the same memory.
1084        assert_eq!(m1.data(&store)[0], 0);
1085        assert_eq!(m2.data(&store)[0], 0);
1086        m1.data_mut(&mut store)[0] = 42;
1087        assert_eq!(m1.data(&mut store)[0], 42);
1088        assert_eq!(m2.data(&mut store)[0], 42);
1089
1090        // And therefore their hash keys are the same.
1091        assert!(m1.hash_key(&store.as_context().0) == m2.hash_key(&store.as_context().0));
1092
1093        // But the hash keys are different from different memories.
1094        let instance2 = Instance::new(&mut store, &module, &[])?;
1095        let m3 = instance2.get_memory(&mut store, "m").unwrap();
1096        assert!(m1.hash_key(&store.as_context().0) != m3.hash_key(&store.as_context().0));
1097
1098        Ok(())
1099    }
1100}