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