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