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