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