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