1 use crate::runtime::vm::{RuntimeLinearMemory, VMMemoryImport}; 2 use crate::store::{StoreData, StoreOpaque, Stored}; 3 use crate::trampoline::generate_memory_export; 4 use crate::Trap; 5 use crate::{AsContext, AsContextMut, Engine, MemoryType, StoreContext, StoreContextMut}; 6 use anyhow::{bail, Result}; 7 use std::cell::UnsafeCell; 8 use std::ops::Range; 9 use std::slice; 10 use std::time::Instant; 11 use wasmtime_environ::MemoryPlan; 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 std::fmt::Display for MemoryAccessError { 24 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { 25 write!(f, "out of bounds memory access") 26 } 27 } 28 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 #[cfg_attr(docsrs, doc(cfg(feature = "async")))] 241 /// Async variant of [`Memory::new`]. You must use this variant with 242 /// [`Store`](`crate::Store`)s which have a 243 /// [`ResourceLimiterAsync`](`crate::ResourceLimiterAsync`). 244 /// 245 /// # Panics 246 /// 247 /// This function will panic when used with a non-async 248 /// [`Store`](`crate::Store`). 249 #[cfg(feature = "async")] 250 pub async fn new_async<T>( 251 mut store: impl AsContextMut<Data = T>, 252 ty: MemoryType, 253 ) -> Result<Memory> 254 where 255 T: Send, 256 { 257 let mut store = store.as_context_mut(); 258 assert!( 259 store.0.async_support(), 260 "cannot use `new_async` without enabling async support on the config" 261 ); 262 store.on_fiber(|store| Self::_new(store.0, ty)).await? 263 } 264 265 /// Helper function for attaching the memory to a "frankenstein" instance 266 fn _new(store: &mut StoreOpaque, ty: MemoryType) -> Result<Memory> { 267 unsafe { 268 let export = generate_memory_export(store, &ty, None)?; 269 Ok(Memory::from_wasmtime_memory(export, store)) 270 } 271 } 272 273 /// Returns the underlying type of this memory. 274 /// 275 /// # Panics 276 /// 277 /// Panics if this memory doesn't belong to `store`. 278 /// 279 /// # Examples 280 /// 281 /// ``` 282 /// # use wasmtime::*; 283 /// # fn main() -> anyhow::Result<()> { 284 /// let engine = Engine::default(); 285 /// let mut store = Store::new(&engine, ()); 286 /// let module = Module::new(&engine, "(module (memory (export \"mem\") 1))")?; 287 /// let instance = Instance::new(&mut store, &module, &[])?; 288 /// let memory = instance.get_memory(&mut store, "mem").unwrap(); 289 /// let ty = memory.ty(&store); 290 /// assert_eq!(ty.minimum(), 1); 291 /// # Ok(()) 292 /// # } 293 /// ``` 294 pub fn ty(&self, store: impl AsContext) -> MemoryType { 295 let store = store.as_context(); 296 let ty = &store[self.0].memory.memory; 297 MemoryType::from_wasmtime_memory(&ty) 298 } 299 300 /// Safely reads memory contents at the given offset into a buffer. 301 /// 302 /// The entire buffer will be filled. 303 /// 304 /// If `offset + buffer.len()` exceed the current memory capacity, then the 305 /// buffer is left untouched and a [`MemoryAccessError`] is returned. 306 /// 307 /// # Panics 308 /// 309 /// Panics if this memory doesn't belong to `store`. 310 pub fn read( 311 &self, 312 store: impl AsContext, 313 offset: usize, 314 buffer: &mut [u8], 315 ) -> Result<(), MemoryAccessError> { 316 let store = store.as_context(); 317 let slice = self 318 .data(&store) 319 .get(offset..) 320 .and_then(|s| s.get(..buffer.len())) 321 .ok_or(MemoryAccessError { _private: () })?; 322 buffer.copy_from_slice(slice); 323 Ok(()) 324 } 325 326 /// Safely writes contents of a buffer to this memory at the given offset. 327 /// 328 /// If the `offset + buffer.len()` exceeds the current memory capacity, then 329 /// none of the buffer is written to memory and a [`MemoryAccessError`] is 330 /// returned. 331 /// 332 /// # Panics 333 /// 334 /// Panics if this memory doesn't belong to `store`. 335 pub fn write( 336 &self, 337 mut store: impl AsContextMut, 338 offset: usize, 339 buffer: &[u8], 340 ) -> Result<(), MemoryAccessError> { 341 let mut context = store.as_context_mut(); 342 self.data_mut(&mut context) 343 .get_mut(offset..) 344 .and_then(|s| s.get_mut(..buffer.len())) 345 .ok_or(MemoryAccessError { _private: () })? 346 .copy_from_slice(buffer); 347 Ok(()) 348 } 349 350 /// Returns this memory as a native Rust slice. 351 /// 352 /// Note that this method will consider the entire store context provided as 353 /// borrowed for the duration of the lifetime of the returned slice. 354 /// 355 /// # Panics 356 /// 357 /// Panics if this memory doesn't belong to `store`. 358 pub fn data<'a, T: 'a>(&self, store: impl Into<StoreContext<'a, T>>) -> &'a [u8] { 359 unsafe { 360 let store = store.into(); 361 let definition = &*store[self.0].definition; 362 debug_assert!(!self.ty(store).is_shared()); 363 slice::from_raw_parts(definition.base, definition.current_length()) 364 } 365 } 366 367 /// Returns this memory as a native Rust mutable 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_mut<'a, T: 'a>(&self, store: impl Into<StoreContextMut<'a, T>>) -> &'a mut [u8] { 376 unsafe { 377 let store = store.into(); 378 let definition = &*store[self.0].definition; 379 debug_assert!(!self.ty(store).is_shared()); 380 slice::from_raw_parts_mut(definition.base, definition.current_length()) 381 } 382 } 383 384 /// Same as [`Memory::data_mut`], but also returns the `T` from the 385 /// [`StoreContextMut`]. 386 /// 387 /// This method can be used when you want to simultaneously work with the 388 /// `T` in the store as well as the memory behind this [`Memory`]. Using 389 /// [`Memory::data_mut`] would consider the entire store borrowed, whereas 390 /// this method allows the Rust compiler to see that the borrow of this 391 /// memory and the borrow of `T` are disjoint. 392 /// 393 /// # Panics 394 /// 395 /// Panics if this memory doesn't belong to `store`. 396 pub fn data_and_store_mut<'a, T: 'a>( 397 &self, 398 store: impl Into<StoreContextMut<'a, T>>, 399 ) -> (&'a mut [u8], &'a mut T) { 400 // Note the unsafety here. Our goal is to simultaneously borrow the 401 // memory and custom data from `store`, and the store it's connected 402 // to. Rust will not let us do that, however, because we must call two 403 // separate methods (both of which borrow the whole `store`) and one of 404 // our borrows is mutable (the custom data). 405 // 406 // This operation, however, is safe because these borrows do not overlap 407 // and in the process of borrowing them mutability doesn't actually 408 // touch anything. This is akin to mutably borrowing two indices in an 409 // array, which is safe so long as the indices are separate. 410 unsafe { 411 let mut store = store.into(); 412 let data = &mut *(store.data_mut() as *mut T); 413 (self.data_mut(store), data) 414 } 415 } 416 417 /// Returns the base pointer, in the host's address space, that the memory 418 /// is located at. 419 /// 420 /// For more information and examples see the documentation on the 421 /// [`Memory`] type. 422 /// 423 /// # Panics 424 /// 425 /// Panics if this memory doesn't belong to `store`. 426 pub fn data_ptr(&self, store: impl AsContext) -> *mut u8 { 427 unsafe { (*store.as_context()[self.0].definition).base } 428 } 429 430 /// Returns the byte length of this memory. 431 /// 432 /// The returned value will be a multiple of the wasm page size, 64k. 433 /// 434 /// For more information and examples see the documentation on the 435 /// [`Memory`] type. 436 /// 437 /// # Panics 438 /// 439 /// Panics if this memory doesn't belong to `store`. 440 pub fn data_size(&self, store: impl AsContext) -> usize { 441 self.internal_data_size(store.as_context().0) 442 } 443 444 pub(crate) fn internal_data_size(&self, store: &StoreOpaque) -> usize { 445 unsafe { (*store[self.0].definition).current_length() } 446 } 447 448 /// Returns the size, in WebAssembly pages, of this wasm memory. 449 /// 450 /// # Panics 451 /// 452 /// Panics if this memory doesn't belong to `store`. 453 pub fn size(&self, store: impl AsContext) -> u64 { 454 self.internal_size(store.as_context().0) 455 } 456 457 pub(crate) fn internal_size(&self, store: &StoreOpaque) -> u64 { 458 (self.internal_data_size(store) / wasmtime_environ::WASM_PAGE_SIZE as usize) as u64 459 } 460 461 /// Grows this WebAssembly memory by `delta` pages. 462 /// 463 /// This will attempt to add `delta` more pages of memory on to the end of 464 /// this `Memory` instance. If successful this may relocate the memory and 465 /// cause [`Memory::data_ptr`] to return a new value. Additionally any 466 /// unsafely constructed slices into this memory may no longer be valid. 467 /// 468 /// On success returns the number of pages this memory previously had 469 /// before the growth succeeded. 470 /// 471 /// # Errors 472 /// 473 /// Returns an error if memory could not be grown, for example if it exceeds 474 /// the maximum limits of this memory. A 475 /// [`ResourceLimiter`](crate::ResourceLimiter) is another example of 476 /// preventing a memory to grow. 477 /// 478 /// # Panics 479 /// 480 /// Panics if this memory doesn't belong to `store`. 481 /// 482 /// This function will panic if the [`Store`](`crate::Store`) has a 483 /// [`ResourceLimiterAsync`](`crate::ResourceLimiterAsync`) (see also: 484 /// [`Store::limiter_async`](`crate::Store::limiter_async`). When using an 485 /// async resource limiter, use [`Memory::grow_async`] instead. 486 /// 487 /// # Examples 488 /// 489 /// ``` 490 /// # use wasmtime::*; 491 /// # fn main() -> anyhow::Result<()> { 492 /// let engine = Engine::default(); 493 /// let mut store = Store::new(&engine, ()); 494 /// let module = Module::new(&engine, "(module (memory (export \"mem\") 1 2))")?; 495 /// let instance = Instance::new(&mut store, &module, &[])?; 496 /// let memory = instance.get_memory(&mut store, "mem").unwrap(); 497 /// 498 /// assert_eq!(memory.size(&store), 1); 499 /// assert_eq!(memory.grow(&mut store, 1)?, 1); 500 /// assert_eq!(memory.size(&store), 2); 501 /// assert!(memory.grow(&mut store, 1).is_err()); 502 /// assert_eq!(memory.size(&store), 2); 503 /// assert_eq!(memory.grow(&mut store, 0)?, 2); 504 /// # Ok(()) 505 /// # } 506 /// ``` 507 pub fn grow(&self, mut store: impl AsContextMut, delta: u64) -> Result<u64> { 508 let store = store.as_context_mut().0; 509 let mem = self.wasmtime_memory(store); 510 unsafe { 511 match (*mem).grow(delta, Some(store))? { 512 Some(size) => { 513 let vm = (*mem).vmmemory(); 514 *store[self.0].definition = vm; 515 Ok(u64::try_from(size).unwrap() / u64::from(wasmtime_environ::WASM_PAGE_SIZE)) 516 } 517 None => bail!("failed to grow memory by `{}`", delta), 518 } 519 } 520 } 521 522 #[cfg_attr(docsrs, doc(cfg(feature = "async")))] 523 /// Async variant of [`Memory::grow`]. Required when using a 524 /// [`ResourceLimiterAsync`](`crate::ResourceLimiterAsync`). 525 /// 526 /// # Panics 527 /// 528 /// This function will panic when used with a non-async 529 /// [`Store`](`crate::Store`). 530 #[cfg(feature = "async")] 531 pub async fn grow_async<T>( 532 &self, 533 mut store: impl AsContextMut<Data = T>, 534 delta: u64, 535 ) -> Result<u64> 536 where 537 T: Send, 538 { 539 let mut store = store.as_context_mut(); 540 assert!( 541 store.0.async_support(), 542 "cannot use `grow_async` without enabling async support on the config" 543 ); 544 store.on_fiber(|store| self.grow(store, delta)).await? 545 } 546 547 fn wasmtime_memory(&self, store: &mut StoreOpaque) -> *mut crate::runtime::vm::Memory { 548 unsafe { 549 let export = &store[self.0]; 550 crate::runtime::vm::Instance::from_vmctx(export.vmctx, |handle| { 551 handle.get_defined_memory(export.index) 552 }) 553 } 554 } 555 556 pub(crate) unsafe fn from_wasmtime_memory( 557 wasmtime_export: crate::runtime::vm::ExportMemory, 558 store: &mut StoreOpaque, 559 ) -> Memory { 560 Memory(store.store_data_mut().insert(wasmtime_export)) 561 } 562 563 pub(crate) fn wasmtime_ty<'a>(&self, store: &'a StoreData) -> &'a wasmtime_environ::Memory { 564 &store[self.0].memory.memory 565 } 566 567 pub(crate) fn vmimport(&self, store: &StoreOpaque) -> crate::runtime::vm::VMMemoryImport { 568 let export = &store[self.0]; 569 crate::runtime::vm::VMMemoryImport { 570 from: export.definition, 571 vmctx: export.vmctx, 572 index: export.index, 573 } 574 } 575 576 pub(crate) fn comes_from_same_store(&self, store: &StoreOpaque) -> bool { 577 store.store_data().contains(self.0) 578 } 579 580 /// Get a stable hash key for this memory. 581 /// 582 /// Even if the same underlying memory definition is added to the 583 /// `StoreData` multiple times and becomes multiple `wasmtime::Memory`s, 584 /// this hash key will be consistent across all of these memories. 585 pub(crate) fn hash_key(&self, store: &StoreOpaque) -> impl std::hash::Hash + Eq { 586 store[self.0].definition as usize 587 } 588 } 589 590 /// A linear memory. This trait provides an interface for raw memory buffers 591 /// which are used by wasmtime, e.g. inside ['Memory']. Such buffers are in 592 /// principle not thread safe. By implementing this trait together with 593 /// MemoryCreator, one can supply wasmtime with custom allocated host managed 594 /// memory. 595 /// 596 /// # Safety 597 /// 598 /// The memory should be page aligned and a multiple of page size. 599 /// To prevent possible silent overflows, the memory should be protected by a 600 /// guard page. Additionally the safety concerns explained in ['Memory'], for 601 /// accessing the memory apply here as well. 602 /// 603 /// Note that this is a relatively new and experimental feature and it is 604 /// recommended to be familiar with wasmtime runtime code to use it. 605 pub unsafe trait LinearMemory: Send + Sync + 'static { 606 /// Returns the number of allocated bytes which are accessible at this time. 607 fn byte_size(&self) -> usize; 608 609 /// Returns the maximum number of bytes the memory can grow to. 610 /// 611 /// Returns `None` if the memory is unbounded, or `Some` if memory cannot 612 /// grow beyond a specified limit. 613 fn maximum_byte_size(&self) -> Option<usize>; 614 615 /// Grows this memory to have the `new_size`, in bytes, specified. 616 /// 617 /// Returns `Err` if memory can't be grown by the specified amount 618 /// of bytes. The error may be downcastable to `std::io::Error`. 619 /// Returns `Ok` if memory was grown successfully. 620 fn grow_to(&mut self, new_size: usize) -> Result<()>; 621 622 /// Return the allocated memory as a mutable pointer to u8. 623 fn as_ptr(&self) -> *mut u8; 624 625 /// Returns the range of native addresses that WebAssembly can natively 626 /// access from this linear memory, including guard pages. 627 fn wasm_accessible(&self) -> Range<usize>; 628 } 629 630 /// A memory creator. Can be used to provide a memory creator 631 /// to wasmtime which supplies host managed memory. 632 /// 633 /// # Safety 634 /// 635 /// This trait is unsafe, as the memory safety depends on proper implementation 636 /// of memory management. Memories created by the MemoryCreator should always be 637 /// treated as owned by wasmtime instance, and any modification of them outside 638 /// of wasmtime invoked routines is unsafe and may lead to corruption. 639 /// 640 /// Note that this is a relatively new and experimental feature and it is 641 /// recommended to be familiar with wasmtime runtime code to use it. 642 pub unsafe trait MemoryCreator: Send + Sync { 643 /// Create a new `LinearMemory` object from the specified parameters. 644 /// 645 /// The type of memory being created is specified by `ty` which indicates 646 /// both the minimum and maximum size, in wasm pages. The minimum and 647 /// maximum sizes, in bytes, are also specified as parameters to avoid 648 /// integer conversion if desired. 649 /// 650 /// The `reserved_size_in_bytes` value indicates the expected size of the 651 /// reservation that is to be made for this memory. If this value is `None` 652 /// than the implementation is free to allocate memory as it sees fit. If 653 /// the value is `Some`, however, then the implementation is expected to 654 /// reserve that many bytes for the memory's allocation, plus the guard 655 /// size at the end. Note that this reservation need only be a virtual 656 /// memory reservation, physical memory does not need to be allocated 657 /// immediately. In this case `grow` should never move the base pointer and 658 /// the maximum size of `ty` is guaranteed to fit within 659 /// `reserved_size_in_bytes`. 660 /// 661 /// The `guard_size_in_bytes` parameter indicates how many bytes of space, 662 /// after the memory allocation, is expected to be unmapped. JIT code will 663 /// elide bounds checks based on the `guard_size_in_bytes` provided, so for 664 /// JIT code to work correctly the memory returned will need to be properly 665 /// guarded with `guard_size_in_bytes` bytes left unmapped after the base 666 /// allocation. 667 /// 668 /// Note that the `reserved_size_in_bytes` and `guard_size_in_bytes` options 669 /// are tuned from the various [`Config`](crate::Config) methods about 670 /// memory sizes/guards. Additionally these two values are guaranteed to be 671 /// multiples of the system page size. 672 /// 673 /// Memory created from this method should be zero filled. 674 fn new_memory( 675 &self, 676 ty: MemoryType, 677 minimum: usize, 678 maximum: Option<usize>, 679 reserved_size_in_bytes: Option<usize>, 680 guard_size_in_bytes: usize, 681 ) -> Result<Box<dyn LinearMemory>, String>; 682 } 683 684 /// A constructor for externally-created shared memory. 685 /// 686 /// The [threads proposal] adds the concept of "shared memory" to WebAssembly. 687 /// This is much the same as a Wasm linear memory (i.e., [`Memory`]), but can be 688 /// used concurrently by multiple agents. Because these agents may execute in 689 /// different threads, [`SharedMemory`] must be thread-safe. 690 /// 691 /// When the threads proposal is enabled, there are multiple ways to construct 692 /// shared memory: 693 /// 1. for imported shared memory, e.g., `(import "env" "memory" (memory 1 1 694 /// shared))`, the user must supply a [`SharedMemory`] with the 695 /// externally-created memory as an import to the instance--e.g., 696 /// `shared_memory.into()`. 697 /// 2. for private or exported shared memory, e.g., `(export "env" "memory" 698 /// (memory 1 1 shared))`, Wasmtime will create the memory internally during 699 /// instantiation--access using `Instance::get_shared_memory()`. 700 /// 701 /// [threads proposal]: 702 /// https://github.com/WebAssembly/threads/blob/master/proposals/threads/Overview.md 703 /// 704 /// # Examples 705 /// 706 /// ``` 707 /// # use wasmtime::*; 708 /// # fn main() -> anyhow::Result<()> { 709 /// let mut config = Config::new(); 710 /// config.wasm_threads(true); 711 /// let engine = Engine::new(&config)?; 712 /// let mut store = Store::new(&engine, ()); 713 /// 714 /// let shared_memory = SharedMemory::new(&engine, MemoryType::shared(1, 2))?; 715 /// let module = Module::new(&engine, r#"(module (memory (import "" "") 1 2 shared))"#)?; 716 /// let instance = Instance::new(&mut store, &module, &[shared_memory.into()])?; 717 /// // ... 718 /// # Ok(()) 719 /// # } 720 /// ``` 721 #[derive(Clone)] 722 pub struct SharedMemory(crate::runtime::vm::SharedMemory, Engine); 723 724 impl SharedMemory { 725 /// Construct a [`SharedMemory`] by providing both the `minimum` and 726 /// `maximum` number of 64K-sized pages. This call allocates the necessary 727 /// pages on the system. 728 #[cfg(feature = "threads")] 729 #[cfg_attr(docsrs, doc(cfg(feature = "threads")))] 730 pub fn new(engine: &Engine, ty: MemoryType) -> Result<Self> { 731 if !ty.is_shared() { 732 bail!("shared memory must have the `shared` flag enabled on its memory type") 733 } 734 debug_assert!(ty.maximum().is_some()); 735 736 let tunables = engine.tunables(); 737 let plan = MemoryPlan::for_memory(ty.wasmtime_memory().clone(), tunables); 738 let memory = crate::runtime::vm::SharedMemory::new(plan)?; 739 Ok(Self(memory, engine.clone())) 740 } 741 742 /// Return the type of the shared memory. 743 pub fn ty(&self) -> MemoryType { 744 MemoryType::from_wasmtime_memory(&self.0.ty()) 745 } 746 747 /// Returns the size, in WebAssembly pages, of this wasm memory. 748 pub fn size(&self) -> u64 { 749 (self.data_size() / wasmtime_environ::WASM_PAGE_SIZE as usize) as u64 750 } 751 752 /// Returns the byte length of this memory. 753 /// 754 /// The returned value will be a multiple of the wasm page size, 64k. 755 /// 756 /// For more information and examples see the documentation on the 757 /// [`Memory`] type. 758 pub fn data_size(&self) -> usize { 759 self.0.byte_size() 760 } 761 762 /// Return access to the available portion of the shared memory. 763 /// 764 /// The slice returned represents the region of accessible memory at the 765 /// time that this function was called. The contents of the returned slice 766 /// will reflect concurrent modifications happening on other threads. 767 /// 768 /// # Safety 769 /// 770 /// The returned slice is valid for the entire duration of the lifetime of 771 /// this instance of [`SharedMemory`]. The base pointer of a shared memory 772 /// does not change. This [`SharedMemory`] may grow further after this 773 /// function has been called, but the slice returned will not grow. 774 /// 775 /// Concurrent modifications may be happening to the data returned on other 776 /// threads. The `UnsafeCell<u8>` represents that safe access to the 777 /// contents of the slice is not possible through normal loads and stores. 778 /// 779 /// The memory returned must be accessed safely through the `Atomic*` types 780 /// in the [`std::sync::atomic`] module. Casting to those types must 781 /// currently be done unsafely. 782 pub fn data(&self) -> &[UnsafeCell<u8>] { 783 unsafe { 784 let definition = &*self.0.vmmemory_ptr(); 785 slice::from_raw_parts(definition.base.cast(), definition.current_length()) 786 } 787 } 788 789 /// Grows this WebAssembly memory by `delta` pages. 790 /// 791 /// This will attempt to add `delta` more pages of memory on to the end of 792 /// this `Memory` instance. If successful this may relocate the memory and 793 /// cause [`Memory::data_ptr`] to return a new value. Additionally any 794 /// unsafely constructed slices into this memory may no longer be valid. 795 /// 796 /// On success returns the number of pages this memory previously had 797 /// before the growth succeeded. 798 /// 799 /// # Errors 800 /// 801 /// Returns an error if memory could not be grown, for example if it exceeds 802 /// the maximum limits of this memory. A 803 /// [`ResourceLimiter`](crate::ResourceLimiter) is another example of 804 /// preventing a memory to grow. 805 pub fn grow(&self, delta: u64) -> Result<u64> { 806 match self.0.grow(delta, None)? { 807 Some((old_size, _new_size)) => { 808 // For shared memory, the `VMMemoryDefinition` is updated inside 809 // the locked region. 810 Ok(u64::try_from(old_size).unwrap() / u64::from(wasmtime_environ::WASM_PAGE_SIZE)) 811 } 812 None => bail!("failed to grow memory by `{}`", delta), 813 } 814 } 815 816 /// Equivalent of the WebAssembly `memory.atomic.notify` instruction for 817 /// this shared memory. 818 /// 819 /// This method allows embedders to notify threads blocked on the specified 820 /// `addr`, an index into wasm linear memory. Threads could include 821 /// wasm threads blocked on a `memory.atomic.wait*` instruction or embedder 822 /// threads blocked on [`SharedMemory::atomic_wait32`], for example. 823 /// 824 /// The `count` argument is the number of threads to wake up. 825 /// 826 /// This function returns the number of threads awoken. 827 /// 828 /// # Errors 829 /// 830 /// This function will return an error if `addr` is not within bounds or 831 /// not aligned to a 4-byte boundary. 832 pub fn atomic_notify(&self, addr: u64, count: u32) -> Result<u32, Trap> { 833 self.0.atomic_notify(addr, count) 834 } 835 836 /// Equivalent of the WebAssembly `memory.atomic.wait32` instruction for 837 /// this shared memory. 838 /// 839 /// This method allows embedders to block the current thread until notified 840 /// via the `memory.atomic.notify` instruction or the 841 /// [`SharedMemory::atomic_notify`] method, enabling synchronization with 842 /// the wasm guest as desired. 843 /// 844 /// The `expected` argument is the expected 32-bit value to be stored at 845 /// the byte address `addr` specified. The `addr` specified is an index 846 /// into this linear memory. 847 /// 848 /// The optional `timeout` argument is the point in time after which the 849 /// calling thread is guaranteed to be woken up. Blocking will not occur 850 /// past this point. 851 /// 852 /// This function returns one of three possible values: 853 /// 854 /// * `WaitResult::Ok` - this function, loaded the value at `addr`, found 855 /// it was equal to `expected`, and then blocked (all as one atomic 856 /// operation). The thread was then awoken with a `memory.atomic.notify` 857 /// instruction or the [`SharedMemory::atomic_notify`] method. 858 /// * `WaitResult::Mismatch` - the value at `addr` was loaded but was not 859 /// equal to `expected` so the thread did not block and immediately 860 /// returned. 861 /// * `WaitResult::TimedOut` - all the steps of `Ok` happened, except this 862 /// thread was woken up due to a timeout. 863 /// 864 /// This function will not return due to spurious wakeups. 865 /// 866 /// # Errors 867 /// 868 /// This function will return an error if `addr` is not within bounds or 869 /// not aligned to a 4-byte boundary. 870 pub fn atomic_wait32( 871 &self, 872 addr: u64, 873 expected: u32, 874 timeout: Option<Instant>, 875 ) -> Result<WaitResult, Trap> { 876 self.0.atomic_wait32(addr, expected, timeout) 877 } 878 879 /// Equivalent of the WebAssembly `memory.atomic.wait64` instruction for 880 /// this shared memory. 881 /// 882 /// For more information see [`SharedMemory::atomic_wait32`]. 883 /// 884 /// # Errors 885 /// 886 /// Returns the same error as [`SharedMemory::atomic_wait32`] except that 887 /// the specified address must be 8-byte aligned instead of 4-byte aligned. 888 pub fn atomic_wait64( 889 &self, 890 addr: u64, 891 expected: u64, 892 timeout: Option<Instant>, 893 ) -> Result<WaitResult, Trap> { 894 self.0.atomic_wait64(addr, expected, timeout) 895 } 896 897 /// Return a reference to the [`Engine`] used to configure the shared 898 /// memory. 899 pub(crate) fn engine(&self) -> &Engine { 900 &self.1 901 } 902 903 /// Construct a single-memory instance to provide a way to import 904 /// [`SharedMemory`] into other modules. 905 pub(crate) fn vmimport(&self, store: &mut StoreOpaque) -> crate::runtime::vm::VMMemoryImport { 906 let export_memory = generate_memory_export(store, &self.ty(), Some(&self.0)).unwrap(); 907 VMMemoryImport { 908 from: export_memory.definition, 909 vmctx: export_memory.vmctx, 910 index: export_memory.index, 911 } 912 } 913 914 /// Create a [`SharedMemory`] from an [`ExportMemory`] definition. This 915 /// function is available to handle the case in which a Wasm module exports 916 /// shared memory and the user wants host-side access to it. 917 pub(crate) unsafe fn from_wasmtime_memory( 918 wasmtime_export: crate::runtime::vm::ExportMemory, 919 store: &mut StoreOpaque, 920 ) -> Self { 921 crate::runtime::vm::Instance::from_vmctx(wasmtime_export.vmctx, |handle| { 922 let memory = handle 923 .get_defined_memory(wasmtime_export.index) 924 .as_mut() 925 .unwrap(); 926 match memory.as_shared_memory() { 927 #[cfg_attr(not(feature = "threads"), allow(unreachable_code))] 928 Some(mem) => Self(mem.clone(), store.engine().clone()), 929 None => panic!("unable to convert from a shared memory"), 930 } 931 }) 932 } 933 } 934 935 impl std::fmt::Debug for SharedMemory { 936 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { 937 f.debug_struct("SharedMemory").finish_non_exhaustive() 938 } 939 } 940 941 #[cfg(test)] 942 mod tests { 943 use crate::*; 944 945 // Assert that creating a memory via `Memory::new` respects the limits/tunables 946 // in `Config`. 947 #[test] 948 fn respect_tunables() { 949 let mut cfg = Config::new(); 950 cfg.static_memory_maximum_size(0) 951 .dynamic_memory_guard_size(0); 952 let mut store = Store::new(&Engine::new(&cfg).unwrap(), ()); 953 let ty = MemoryType::new(1, None); 954 let mem = Memory::new(&mut store, ty).unwrap(); 955 let store = store.as_context(); 956 assert_eq!(store[mem.0].memory.offset_guard_size, 0); 957 match &store[mem.0].memory.style { 958 wasmtime_environ::MemoryStyle::Dynamic { .. } => {} 959 other => panic!("unexpected style {:?}", other), 960 } 961 } 962 963 #[test] 964 fn hash_key_is_stable_across_duplicate_store_data_entries() -> Result<()> { 965 let mut store = Store::<()>::default(); 966 let module = Module::new( 967 store.engine(), 968 r#" 969 (module 970 (memory (export "m") 1 1) 971 ) 972 "#, 973 )?; 974 let instance = Instance::new(&mut store, &module, &[])?; 975 976 // Each time we `get_memory`, we call `Memory::from_wasmtime` which adds 977 // a new entry to `StoreData`, so `g1` and `g2` will have different 978 // indices into `StoreData`. 979 let m1 = instance.get_memory(&mut store, "m").unwrap(); 980 let m2 = instance.get_memory(&mut store, "m").unwrap(); 981 982 // That said, they really point to the same memory. 983 assert_eq!(m1.data(&store)[0], 0); 984 assert_eq!(m2.data(&store)[0], 0); 985 m1.data_mut(&mut store)[0] = 42; 986 assert_eq!(m1.data(&mut store)[0], 42); 987 assert_eq!(m2.data(&mut store)[0], 42); 988 989 // And therefore their hash keys are the same. 990 assert!(m1.hash_key(&store.as_context().0) == m2.hash_key(&store.as_context().0)); 991 992 // But the hash keys are different from different memories. 993 let instance2 = Instance::new(&mut store, &module, &[])?; 994 let m3 = instance2.get_memory(&mut store, "m").unwrap(); 995 assert!(m1.hash_key(&store.as_context().0) != m3.hash_key(&store.as_context().0)); 996 997 Ok(()) 998 } 999 } 1000