1 //! An `Instance` contains all the runtime state used by execution of a 2 //! wasm module (except its callstack and register state). An 3 //! `InstanceHandle` is a reference-counting handle for an `Instance`. 4 5 use crate::prelude::*; 6 use crate::runtime::vm::const_expr::{ConstEvalContext, ConstExprEvaluator}; 7 use crate::runtime::vm::export::Export; 8 use crate::runtime::vm::memory::{Memory, RuntimeMemoryCreator}; 9 use crate::runtime::vm::table::{Table, TableElement, TableElementType}; 10 use crate::runtime::vm::vmcontext::{ 11 VMBuiltinFunctionsArray, VMContext, VMFuncRef, VMFunctionImport, VMGlobalDefinition, 12 VMGlobalImport, VMMemoryDefinition, VMMemoryImport, VMOpaqueContext, VMStoreContext, 13 VMTableDefinition, VMTableImport, VMTagDefinition, VMTagImport, 14 }; 15 use crate::runtime::vm::{ 16 ExportFunction, ExportGlobal, ExportGlobalKind, ExportMemory, ExportTable, ExportTag, GcStore, 17 Imports, ModuleRuntimeInfo, SendSyncPtr, VMGcRef, VMStore, VMStoreRawPtr, VmPtr, VmSafe, 18 WasmFault, 19 }; 20 use crate::store::{InstanceId, StoreOpaque}; 21 use alloc::sync::Arc; 22 use core::alloc::Layout; 23 use core::ops::Range; 24 use core::pin::Pin; 25 use core::ptr::NonNull; 26 #[cfg(target_has_atomic = "64")] 27 use core::sync::atomic::AtomicU64; 28 use core::{mem, ptr}; 29 #[cfg(feature = "gc")] 30 use wasmtime_environ::ModuleInternedTypeIndex; 31 use wasmtime_environ::{ 32 DataIndex, DefinedGlobalIndex, DefinedMemoryIndex, DefinedTableIndex, DefinedTagIndex, 33 ElemIndex, EntityIndex, EntityRef, EntitySet, FuncIndex, GlobalIndex, HostPtr, MemoryIndex, 34 Module, PrimaryMap, PtrSize, TableIndex, TableInitialValue, TableSegmentElements, TagIndex, 35 Trap, VMCONTEXT_MAGIC, VMOffsets, VMSharedTypeIndex, WasmHeapTopType, 36 packed_option::ReservedValue, 37 }; 38 #[cfg(feature = "wmemcheck")] 39 use wasmtime_wmemcheck::Wmemcheck; 40 41 mod allocator; 42 pub use allocator::*; 43 44 /// The pair of an instance and a raw pointer its associated store. 45 /// 46 /// ### Safety 47 /// 48 /// > **Note**: it's known that the documentation below is documenting an 49 /// > unsound pattern and we're in the process of fixing it, but it'll take 50 /// > some time to refactor. Notably `unpack_mut` is not sound because the 51 /// > returned store pointer can be used to accidentally alias the instance 52 /// > pointer returned as well. 53 /// 54 /// Getting a borrow of a vmctx's store is one of the fundamental bits of unsafe 55 /// code in Wasmtime. No matter how we architect the runtime, some kind of 56 /// unsafe conversion from a raw vmctx pointer that Wasm is using into a Rust 57 /// struct must happen. 58 /// 59 /// It is our responsibility to ensure that multiple (exclusive) borrows of the 60 /// vmctx's store never exist at the same time. The distinction between the 61 /// `Instance` type (which doesn't expose its underlying vmctx pointer or a way 62 /// to get a borrow of its associated store) and this type (which does) is 63 /// designed to help with that. 64 /// 65 /// Going from a `*mut VMContext` to a `&mut StoreInner<T>` is naturally unsafe 66 /// due to the raw pointer usage, but additionally the `T` type parameter needs 67 /// to be the same `T` that was used to define the `dyn VMStore` trait object 68 /// that was stuffed into the vmctx. 69 /// 70 /// ### Usage 71 /// 72 /// Usage generally looks like: 73 /// 74 /// 1. You get a raw `*mut VMContext` from Wasm 75 /// 76 /// 2. You call `InstanceAndStore::from_vmctx` on that raw pointer 77 /// 78 /// 3. You then call `InstanceAndStore::unpack_mut` (or another helper) to get 79 /// the underlying `Pin<&mut Instance>` and `&mut dyn VMStore` (or `&mut 80 /// StoreInner<T>`). 81 /// 82 /// 4. You then use whatever `Instance` methods you need to, each of which take 83 /// a store argument as necessary. 84 /// 85 /// In step (4) you no longer need to worry about double exclusive borrows of 86 /// the store, so long as you don't do (1-2) again. Note also that the borrow 87 /// checker prevents repeating step (3) if you never repeat (1-2). In general, 88 /// steps (1-3) should be done in a single, common, internally-unsafe, 89 /// plumbing-code bottleneck and the raw pointer should never be exposed to Rust 90 /// code that does (4) after the `InstanceAndStore` is created. Follow this 91 /// pattern, and everything using the resulting `Instance` and `Store` can be 92 /// safe code (at least, with regards to accessing the store itself). 93 /// 94 /// As an illustrative example, the common plumbing code for our various 95 /// libcalls performs steps (1-3) before calling into each actual libcall 96 /// implementation function that does (4). The plumbing code hides the raw vmctx 97 /// pointer and never gives out access to it to the libcall implementation 98 /// functions, nor does an `Instance` expose its internal vmctx pointer, which 99 /// would allow unsafely repeating steps (1-2). 100 #[repr(transparent)] 101 pub struct InstanceAndStore { 102 instance: Instance, 103 } 104 105 impl InstanceAndStore { 106 /// Converts the provided `*mut VMContext` to an `InstanceAndStore` 107 /// reference and calls the provided closure with it. 108 /// 109 /// This method will move the `vmctx` pointer backwards to point to the 110 /// original `Instance` that precedes it. The closure is provided a 111 /// temporary reference to the `InstanceAndStore` with a constrained 112 /// lifetime to ensure that it doesn't accidentally escape. 113 /// 114 /// # Safety 115 /// 116 /// Callers must validate that the `vmctx` pointer is a valid allocation and 117 /// that it's valid to acquire `&mut InstanceAndStore` at this time. For 118 /// example this can't be called twice on the same `VMContext` to get two 119 /// active mutable borrows to the same `InstanceAndStore`. 120 /// 121 /// See also the safety discussion in this type's documentation. 122 #[inline] 123 pub(crate) unsafe fn from_vmctx<R>( 124 vmctx: NonNull<VMContext>, 125 f: impl for<'a> FnOnce(&'a mut Self) -> R, 126 ) -> R { 127 const _: () = assert!(mem::size_of::<InstanceAndStore>() == mem::size_of::<Instance>()); 128 let mut ptr = vmctx 129 .byte_sub(mem::size_of::<Instance>()) 130 .cast::<InstanceAndStore>(); 131 132 f(ptr.as_mut()) 133 } 134 135 /// Unpacks this `InstanceAndStore` into its underlying `Instance` and `dyn 136 /// VMStore`. 137 #[inline] 138 pub(crate) fn unpack_mut(&mut self) -> (Pin<&mut Instance>, &mut dyn VMStore) { 139 unsafe { 140 let store = &mut *self.store_ptr(); 141 (Pin::new_unchecked(&mut self.instance), store) 142 } 143 } 144 145 /// Gets a pointer to this instance's `Store` which was originally 146 /// configured on creation. 147 /// 148 /// # Panics 149 /// 150 /// May panic if the originally configured store was `None`. That can happen 151 /// for host functions so host functions can't be queried what their 152 /// original `Store` was since it's just retained as null (since host 153 /// functions are shared amongst threads and don't all share the same 154 /// store). 155 #[inline] 156 fn store_ptr(&self) -> *mut dyn VMStore { 157 self.instance.store.unwrap().0.as_ptr() 158 } 159 } 160 161 /// A type that roughly corresponds to a WebAssembly instance, but is also used 162 /// for host-defined objects. 163 /// 164 /// Instances here can correspond to actual instantiated modules, but it's also 165 /// used ubiquitously for host-defined objects. For example creating a 166 /// host-defined memory will have a `module` that looks like it exports a single 167 /// memory (and similar for other constructs). 168 /// 169 /// This `Instance` type is used as a ubiquitous representation for WebAssembly 170 /// values, whether or not they were created on the host or through a module. 171 /// 172 /// # Ownership 173 /// 174 /// This structure is never allocated directly but is instead managed through 175 /// an `InstanceHandle`. This structure ends with a `VMContext` which has a 176 /// dynamic size corresponding to the `module` configured within. Memory 177 /// management of this structure is always done through `InstanceHandle` as the 178 /// sole owner of an instance. 179 /// 180 /// # `Instance` and `Pin` 181 /// 182 /// Given an instance it is accompanied with trailing memory for the 183 /// appropriate `VMContext`. The `Instance` also holds `runtime_info` and other 184 /// information pointing to relevant offsets for the `VMContext`. Thus it is 185 /// not sound to mutate `runtime_info` after an instance is created. More 186 /// generally it's also not safe to "swap" instances, for example given two 187 /// `&mut Instance` values it's not sound to swap them as then the `VMContext` 188 /// values are inaccurately described. 189 /// 190 /// To encapsulate this guarantee this type is only ever mutated through Rust's 191 /// `Pin` type. All mutable methods here take `self: Pin<&mut Self>` which 192 /// statically disallows safe access to `&mut Instance`. There are assorted 193 /// "projection methods" to go from `Pin<&mut Instance>` to `&mut T` for 194 /// individual fields, for example `memories_mut`. More methods can be added as 195 /// necessary or methods may also be added to project multiple fields at a time 196 /// if necessary to. The precise ergonomics around getting mutable access to 197 /// some fields (but notably not `runtime_info`) is probably going to evolve 198 /// over time. 199 /// 200 /// Note that is is not sound to basically ever pass around `&mut Instance`. 201 /// That should always instead be `Pin<&mut Instance>`. All usage of 202 /// `Pin::new_unchecked` should be here in this module in just a few `unsafe` 203 /// locations and it's recommended to use existing helpers if you can. 204 #[repr(C)] // ensure that the vmctx field is last. 205 pub struct Instance { 206 /// The index, within a `Store` that this instance lives at 207 id: InstanceId, 208 209 /// The runtime info (corresponding to the "compiled module" 210 /// abstraction in higher layers) that is retained and needed for 211 /// lazy initialization. This provides access to the underlying 212 /// Wasm module entities, the compiled JIT code, metadata about 213 /// functions, lazy initialization state, etc. 214 runtime_info: ModuleRuntimeInfo, 215 216 /// WebAssembly linear memory data. 217 /// 218 /// This is where all runtime information about defined linear memories in 219 /// this module lives. 220 /// 221 /// The `MemoryAllocationIndex` was given from our `InstanceAllocator` and 222 /// must be given back to the instance allocator when deallocating each 223 /// memory. 224 memories: PrimaryMap<DefinedMemoryIndex, (MemoryAllocationIndex, Memory)>, 225 226 /// WebAssembly table data. 227 /// 228 /// Like memories, this is only for defined tables in the module and 229 /// contains all of their runtime state. 230 /// 231 /// The `TableAllocationIndex` was given from our `InstanceAllocator` and 232 /// must be given back to the instance allocator when deallocating each 233 /// table. 234 tables: PrimaryMap<DefinedTableIndex, (TableAllocationIndex, Table)>, 235 236 /// Stores the dropped passive element segments in this instantiation by index. 237 /// If the index is present in the set, the segment has been dropped. 238 dropped_elements: EntitySet<ElemIndex>, 239 240 /// Stores the dropped passive data segments in this instantiation by index. 241 /// If the index is present in the set, the segment has been dropped. 242 dropped_data: EntitySet<DataIndex>, 243 244 /// A pointer to the `vmctx` field at the end of the `Instance`. 245 /// 246 /// If you're looking at this a reasonable question would be "why do we need 247 /// a pointer to ourselves?" because after all the pointer's value is 248 /// trivially derivable from any `&Instance` pointer. The rationale for this 249 /// field's existence is subtle, but it's required for correctness. The 250 /// short version is "this makes miri happy". 251 /// 252 /// The long version of why this field exists is that the rules that MIRI 253 /// uses to ensure pointers are used correctly have various conditions on 254 /// them depend on how pointers are used. More specifically if `*mut T` is 255 /// derived from `&mut T`, then that invalidates all prior pointers drived 256 /// from the `&mut T`. This means that while we liberally want to re-acquire 257 /// a `*mut VMContext` throughout the implementation of `Instance` the 258 /// trivial way, a function `fn vmctx(Pin<&mut Instance>) -> *mut VMContext` 259 /// would effectively invalidate all prior `*mut VMContext` pointers 260 /// acquired. The purpose of this field is to serve as a sort of 261 /// source-of-truth for where `*mut VMContext` pointers come from. 262 /// 263 /// This field is initialized when the `Instance` is created with the 264 /// original allocation's pointer. That means that the provenance of this 265 /// pointer contains the entire allocation (both instance and `VMContext`). 266 /// This provenance bit is then "carried through" where `fn vmctx` will base 267 /// all returned pointers on this pointer itself. This provides the means of 268 /// never invalidating this pointer throughout MIRI and additionally being 269 /// able to still temporarily have `Pin<&mut Instance>` methods and such. 270 /// 271 /// It's important to note, though, that this is not here purely for MIRI. 272 /// The careful construction of the `fn vmctx` method has ramifications on 273 /// the LLVM IR generated, for example. A historical CVE on Wasmtime, 274 /// GHSA-ch89-5g45-qwc7, was caused due to relying on undefined behavior. By 275 /// deriving VMContext pointers from this pointer it specifically hints to 276 /// LLVM that trickery is afoot and it properly informs `noalias` and such 277 /// annotations and analysis. More-or-less this pointer is actually loaded 278 /// in LLVM IR which helps defeat otherwise present aliasing optimizations, 279 /// which we want, since writes to this should basically never be optimized 280 /// out. 281 /// 282 /// As a final note it's worth pointing out that the machine code generated 283 /// for accessing `fn vmctx` is still as one would expect. This member isn't 284 /// actually ever loaded at runtime (or at least shouldn't be). Perhaps in 285 /// the future if the memory consumption of this field is a problem we could 286 /// shrink it slightly, but for now one extra pointer per wasm instance 287 /// seems not too bad. 288 vmctx_self_reference: SendSyncPtr<VMContext>, 289 290 // TODO: add support for multiple memories; `wmemcheck_state` corresponds to 291 // memory 0. 292 #[cfg(feature = "wmemcheck")] 293 pub(crate) wmemcheck_state: Option<Wmemcheck>, 294 295 /// Self-pointer back to `Store<T>` and its functions. Not present for 296 /// the brief time that `Store<T>` is itself being created. Also not 297 /// present for some niche uses that are disconnected from stores (e.g. 298 /// cross-thread stuff used in `InstancePre`) 299 store: Option<VMStoreRawPtr>, 300 301 /// Additional context used by compiled wasm code. This field is last, and 302 /// represents a dynamically-sized array that extends beyond the nominal 303 /// end of the struct (similar to a flexible array member). 304 vmctx: VMContext, 305 } 306 307 impl Instance { 308 /// Create an instance at the given memory address. 309 /// 310 /// It is assumed the memory was properly aligned and the 311 /// allocation was `alloc_size` in bytes. 312 unsafe fn new( 313 req: InstanceAllocationRequest, 314 memories: PrimaryMap<DefinedMemoryIndex, (MemoryAllocationIndex, Memory)>, 315 tables: PrimaryMap<DefinedTableIndex, (TableAllocationIndex, Table)>, 316 memory_tys: &PrimaryMap<MemoryIndex, wasmtime_environ::Memory>, 317 ) -> InstanceHandle { 318 // The allocation must be *at least* the size required of `Instance`. 319 let layout = Self::alloc_layout(req.runtime_info.offsets()); 320 let ptr = alloc::alloc::alloc(layout); 321 if ptr.is_null() { 322 alloc::alloc::handle_alloc_error(layout); 323 } 324 let ptr = ptr.cast::<Instance>(); 325 326 let module = req.runtime_info.env_module(); 327 let dropped_elements = EntitySet::with_capacity(module.passive_elements.len()); 328 let dropped_data = EntitySet::with_capacity(module.passive_data_map.len()); 329 330 #[cfg(not(feature = "wmemcheck"))] 331 let _ = memory_tys; 332 333 ptr::write( 334 ptr, 335 Instance { 336 id: req.id, 337 runtime_info: req.runtime_info.clone(), 338 memories, 339 tables, 340 dropped_elements, 341 dropped_data, 342 vmctx_self_reference: SendSyncPtr::new(NonNull::new(ptr.add(1).cast()).unwrap()), 343 vmctx: VMContext { 344 _marker: core::marker::PhantomPinned, 345 }, 346 #[cfg(feature = "wmemcheck")] 347 wmemcheck_state: { 348 if req.wmemcheck { 349 let size = memory_tys 350 .iter() 351 .next() 352 .map(|memory| memory.1.limits.min) 353 .unwrap_or(0) 354 * 64 355 * 1024; 356 Some(Wmemcheck::new(size as usize)) 357 } else { 358 None 359 } 360 }, 361 store: None, 362 }, 363 ); 364 365 let mut ret = InstanceHandle { 366 instance: SendSyncPtr::new(NonNull::new(ptr).unwrap()), 367 }; 368 ret.get_mut() 369 .initialize_vmctx(module, req.runtime_info.offsets(), req.store, req.imports); 370 ret 371 } 372 373 /// Converts the provided `*mut VMContext` to an `Instance` pointer and runs 374 /// the provided closure with the instance. 375 /// 376 /// This method will move the `vmctx` pointer backwards to point to the 377 /// original `Instance` that precedes it. The closure is provided a 378 /// temporary version of the `Instance` pointer with a constrained lifetime 379 /// to the closure to ensure it doesn't accidentally escape. 380 /// 381 /// # Unsafety 382 /// 383 /// Callers must validate that the `vmctx` pointer is a valid allocation 384 /// and that it's valid to acquire `Pin<&mut Instance>` at this time. For example 385 /// this can't be called twice on the same `VMContext` to get two active 386 /// pointers to the same `Instance`. 387 #[inline] 388 pub unsafe fn from_vmctx<R>( 389 vmctx: NonNull<VMContext>, 390 f: impl FnOnce(Pin<&mut Instance>) -> R, 391 ) -> R { 392 let mut ptr = vmctx 393 .byte_sub(mem::size_of::<Instance>()) 394 .cast::<Instance>(); 395 f(Pin::new_unchecked(ptr.as_mut())) 396 } 397 398 /// Helper function to access various locations offset from our `*mut 399 /// VMContext` object. 400 /// 401 /// Note that this method takes `&self` as an argument but returns 402 /// `NonNull<T>` which is frequently used to mutate said memory. This is an 403 /// intentional design decision where the safety of the modification of 404 /// memory is placed as a burden onto the caller. The implementation of this 405 /// method explicitly does not require `&mut self` to acquire mutable 406 /// provenance to update the `VMContext` region. Instead all pointers into 407 /// the `VMContext` area have provenance/permissions to write. 408 /// 409 /// Also note though that care must be taken to ensure that reads/writes of 410 /// memory must only happen where appropriate, for example a non-atomic 411 /// write (as most are) should never happen concurrently with another read 412 /// or write. It's generally on the burden of the caller to adhere to this. 413 /// 414 /// Also of note is that most of the time the usage of this method falls 415 /// into one of: 416 /// 417 /// * Something in the VMContext is being read or written. In that case use 418 /// `vmctx_plus_offset` or `vmctx_plus_offset_mut` if possible due to 419 /// that having a safer lifetime. 420 /// 421 /// * A pointer is being created to pass to other VM* data structures. In 422 /// that situation the lifetime of all VM data structures are typically 423 /// tied to the `Store<T>` which is what provides the guarantees around 424 /// concurrency/etc. 425 /// 426 /// There's quite a lot of unsafety riding on this method, especially 427 /// related to the ascription `T` of the byte `offset`. It's hoped that in 428 /// the future we're able to settle on an in theory safer design. 429 /// 430 /// # Safety 431 /// 432 /// This method is unsafe because the `offset` must be within bounds of the 433 /// `VMContext` object trailing this instance. Additionally `T` must be a 434 /// valid ascription of the value that resides at that location. 435 unsafe fn vmctx_plus_offset_raw<T: VmSafe>(&self, offset: impl Into<u32>) -> NonNull<T> { 436 // SAFETY: the safety requirements of `byte_add` are forwarded to this 437 // method's caller. 438 unsafe { 439 self.vmctx() 440 .byte_add(usize::try_from(offset.into()).unwrap()) 441 .cast() 442 } 443 } 444 445 /// Helper above `vmctx_plus_offset_raw` which transfers the lifetime of 446 /// `&self` to the returned reference `&T`. 447 /// 448 /// # Safety 449 /// 450 /// See the safety documentation of `vmctx_plus_offset_raw`. 451 unsafe fn vmctx_plus_offset<T: VmSafe>(&self, offset: impl Into<u32>) -> &T { 452 // SAFETY: this method has the same safety requirements as 453 // `vmctx_plus_offset_raw`. 454 unsafe { self.vmctx_plus_offset_raw(offset).as_ref() } 455 } 456 457 /// Helper above `vmctx_plus_offset_raw` which transfers the lifetime of 458 /// `&mut self` to the returned reference `&mut T`. 459 /// 460 /// # Safety 461 /// 462 /// See the safety documentation of `vmctx_plus_offset_raw`. 463 unsafe fn vmctx_plus_offset_mut<T: VmSafe>( 464 self: Pin<&mut Self>, 465 offset: impl Into<u32>, 466 ) -> &mut T { 467 // SAFETY: this method has the same safety requirements as 468 // `vmctx_plus_offset_raw`. 469 unsafe { self.vmctx_plus_offset_raw(offset).as_mut() } 470 } 471 472 pub(crate) fn env_module(&self) -> &Arc<wasmtime_environ::Module> { 473 self.runtime_info.env_module() 474 } 475 476 #[cfg(feature = "gc")] 477 pub(crate) fn runtime_module(&self) -> Option<&crate::Module> { 478 match &self.runtime_info { 479 ModuleRuntimeInfo::Module(m) => Some(m), 480 ModuleRuntimeInfo::Bare(_) => None, 481 } 482 } 483 484 /// Translate a module-level interned type index into an engine-level 485 /// interned type index. 486 #[cfg(feature = "gc")] 487 pub fn engine_type_index(&self, module_index: ModuleInternedTypeIndex) -> VMSharedTypeIndex { 488 self.runtime_info.engine_type_index(module_index) 489 } 490 491 #[inline] 492 fn offsets(&self) -> &VMOffsets<HostPtr> { 493 self.runtime_info.offsets() 494 } 495 496 /// Return the indexed `VMFunctionImport`. 497 fn imported_function(&self, index: FuncIndex) -> &VMFunctionImport { 498 unsafe { self.vmctx_plus_offset(self.offsets().vmctx_vmfunction_import(index)) } 499 } 500 501 /// Return the index `VMTableImport`. 502 fn imported_table(&self, index: TableIndex) -> &VMTableImport { 503 unsafe { self.vmctx_plus_offset(self.offsets().vmctx_vmtable_import(index)) } 504 } 505 506 /// Return the indexed `VMMemoryImport`. 507 fn imported_memory(&self, index: MemoryIndex) -> &VMMemoryImport { 508 unsafe { self.vmctx_plus_offset(self.offsets().vmctx_vmmemory_import(index)) } 509 } 510 511 /// Return the indexed `VMGlobalImport`. 512 fn imported_global(&self, index: GlobalIndex) -> &VMGlobalImport { 513 unsafe { self.vmctx_plus_offset(self.offsets().vmctx_vmglobal_import(index)) } 514 } 515 516 /// Return the indexed `VMTagImport`. 517 fn imported_tag(&self, index: TagIndex) -> &VMTagImport { 518 unsafe { self.vmctx_plus_offset(self.offsets().vmctx_vmtag_import(index)) } 519 } 520 521 /// Return the indexed `VMTagDefinition`. 522 pub fn tag_ptr(&self, index: DefinedTagIndex) -> NonNull<VMTagDefinition> { 523 unsafe { self.vmctx_plus_offset_raw(self.offsets().vmctx_vmtag_definition(index)) } 524 } 525 526 /// Return the indexed `VMTableDefinition`. 527 pub fn table(&self, index: DefinedTableIndex) -> VMTableDefinition { 528 unsafe { self.table_ptr(index).read() } 529 } 530 531 /// Updates the value for a defined table to `VMTableDefinition`. 532 fn set_table(self: Pin<&mut Self>, index: DefinedTableIndex, table: VMTableDefinition) { 533 unsafe { 534 self.table_ptr(index).write(table); 535 } 536 } 537 538 /// Return a pointer to the `index`'th table within this instance, stored 539 /// in vmctx memory. 540 pub fn table_ptr(&self, index: DefinedTableIndex) -> NonNull<VMTableDefinition> { 541 unsafe { self.vmctx_plus_offset_raw(self.offsets().vmctx_vmtable_definition(index)) } 542 } 543 544 /// Get a locally defined or imported memory. 545 pub(crate) fn get_memory(&self, index: MemoryIndex) -> VMMemoryDefinition { 546 if let Some(defined_index) = self.env_module().defined_memory_index(index) { 547 self.memory(defined_index) 548 } else { 549 let import = self.imported_memory(index); 550 unsafe { VMMemoryDefinition::load(import.from.as_ptr()) } 551 } 552 } 553 554 /// Get a locally defined or imported memory. 555 #[cfg(feature = "threads")] 556 pub(crate) fn get_runtime_memory(self: Pin<&mut Self>, index: MemoryIndex) -> &mut Memory { 557 if let Some(defined_index) = self.env_module().defined_memory_index(index) { 558 unsafe { &mut *self.get_defined_memory(defined_index) } 559 } else { 560 let import = self.imported_memory(index); 561 unsafe { 562 let ptr = Instance::from_vmctx(import.vmctx.as_non_null(), |i| { 563 i.get_defined_memory(import.index) 564 }); 565 &mut *ptr 566 } 567 } 568 } 569 570 /// Return the indexed `VMMemoryDefinition`, loaded from vmctx memory 571 /// already. 572 pub fn memory(&self, index: DefinedMemoryIndex) -> VMMemoryDefinition { 573 unsafe { VMMemoryDefinition::load(self.memory_ptr(index).as_ptr()) } 574 } 575 576 /// Set the indexed memory to `VMMemoryDefinition`. 577 fn set_memory(&self, index: DefinedMemoryIndex, mem: VMMemoryDefinition) { 578 unsafe { 579 self.memory_ptr(index).write(mem); 580 } 581 } 582 583 /// Return the address of the specified memory at `index` within this vmctx. 584 /// 585 /// Note that the returned pointer resides in wasm-code-readable-memory in 586 /// the vmctx. 587 pub fn memory_ptr(&self, index: DefinedMemoryIndex) -> NonNull<VMMemoryDefinition> { 588 unsafe { 589 self.vmctx_plus_offset::<VmPtr<_>>(self.offsets().vmctx_vmmemory_pointer(index)) 590 .as_non_null() 591 } 592 } 593 594 /// Return the indexed `VMGlobalDefinition`. 595 pub fn global_ptr(&self, index: DefinedGlobalIndex) -> NonNull<VMGlobalDefinition> { 596 unsafe { self.vmctx_plus_offset_raw(self.offsets().vmctx_vmglobal_definition(index)) } 597 } 598 599 /// Get a raw pointer to the global at the given index regardless whether it 600 /// is defined locally or imported from another module. 601 /// 602 /// Panics if the index is out of bound or is the reserved value. 603 pub(crate) fn defined_or_imported_global_ptr( 604 self: Pin<&mut Self>, 605 index: GlobalIndex, 606 ) -> NonNull<VMGlobalDefinition> { 607 if let Some(index) = self.env_module().defined_global_index(index) { 608 self.global_ptr(index) 609 } else { 610 self.imported_global(index).from.as_non_null() 611 } 612 } 613 614 /// Get all globals within this instance. 615 /// 616 /// Returns both import and defined globals. 617 /// 618 /// Returns both exported and non-exported globals. 619 /// 620 /// Gives access to the full globals space. 621 pub fn all_globals(&self) -> impl ExactSizeIterator<Item = (GlobalIndex, ExportGlobal)> + '_ { 622 let module = self.env_module().clone(); 623 module 624 .globals 625 .keys() 626 .map(move |idx| (idx, self.get_exported_global(idx))) 627 } 628 629 /// Get the globals defined in this instance (not imported). 630 pub fn defined_globals( 631 &self, 632 ) -> impl ExactSizeIterator<Item = (DefinedGlobalIndex, ExportGlobal)> + '_ { 633 let module = self.env_module().clone(); 634 module 635 .globals 636 .keys() 637 .skip(module.num_imported_globals) 638 .map(move |global_idx| { 639 let def_idx = module.defined_global_index(global_idx).unwrap(); 640 let global = ExportGlobal { 641 definition: self.global_ptr(def_idx), 642 kind: ExportGlobalKind::Instance(self.vmctx(), def_idx), 643 global: self.env_module().globals[global_idx], 644 }; 645 (def_idx, global) 646 }) 647 } 648 649 /// Return a pointer to the interrupts structure 650 #[inline] 651 pub fn vm_store_context(&self) -> NonNull<Option<VmPtr<VMStoreContext>>> { 652 unsafe { self.vmctx_plus_offset_raw(self.offsets().ptr.vmctx_store_context()) } 653 } 654 655 /// Return a pointer to the global epoch counter used by this instance. 656 #[cfg(target_has_atomic = "64")] 657 pub fn epoch_ptr(self: Pin<&mut Self>) -> &mut Option<VmPtr<AtomicU64>> { 658 let offset = self.offsets().ptr.vmctx_epoch_ptr(); 659 unsafe { self.vmctx_plus_offset_mut(offset) } 660 } 661 662 /// Return a pointer to the collector-specific heap data. 663 pub fn gc_heap_data(self: Pin<&mut Self>) -> &mut Option<VmPtr<u8>> { 664 let offset = self.offsets().ptr.vmctx_gc_heap_data(); 665 unsafe { self.vmctx_plus_offset_mut(offset) } 666 } 667 668 pub(crate) unsafe fn set_store(mut self: Pin<&mut Self>, store: Option<NonNull<dyn VMStore>>) { 669 *self.as_mut().store_mut() = store.map(VMStoreRawPtr); 670 if let Some(mut store) = store { 671 let store = store.as_mut(); 672 self.vm_store_context() 673 .write(Some(store.vm_store_context_ptr().into())); 674 #[cfg(target_has_atomic = "64")] 675 { 676 *self.as_mut().epoch_ptr() = 677 Some(NonNull::from(store.engine().epoch_counter()).into()); 678 } 679 680 if self.env_module().needs_gc_heap { 681 self.as_mut().set_gc_heap(Some(store.gc_store().expect( 682 "if we need a GC heap, then `Instance::new_raw` should have already \ 683 allocated it for us", 684 ))); 685 } else { 686 self.as_mut().set_gc_heap(None); 687 } 688 } else { 689 self.vm_store_context().write(None); 690 #[cfg(target_has_atomic = "64")] 691 { 692 *self.as_mut().epoch_ptr() = None; 693 } 694 self.as_mut().set_gc_heap(None); 695 } 696 } 697 698 unsafe fn set_gc_heap(self: Pin<&mut Self>, gc_store: Option<&GcStore>) { 699 if let Some(gc_store) = gc_store { 700 *self.gc_heap_data() = Some(gc_store.gc_heap.vmctx_gc_heap_data().into()); 701 } else { 702 *self.gc_heap_data() = None; 703 } 704 } 705 706 /// Return a reference to the vmctx used by compiled wasm code. 707 #[inline] 708 pub fn vmctx(&self) -> NonNull<VMContext> { 709 // The definition of this method is subtle but intentional. The goal 710 // here is that effectively this should return `&mut self.vmctx`, but 711 // it's not quite so simple. Some more documentation is available on the 712 // `vmctx_self_reference` field, but the general idea is that we're 713 // creating a pointer to return with proper provenance. Provenance is 714 // still in the works in Rust at the time of this writing but the load 715 // of the `self.vmctx_self_reference` field is important here as it 716 // affects how LLVM thinks about aliasing with respect to the returned 717 // pointer. 718 // 719 // The intention of this method is to codegen to machine code as `&mut 720 // self.vmctx`, however. While it doesn't show up like this in LLVM IR 721 // (there's an actual load of the field) it does look like that by the 722 // time the backend runs. (that's magic to me, the backend removing 723 // loads...) 724 let addr = &raw const self.vmctx; 725 let ret = self.vmctx_self_reference.as_ptr().with_addr(addr.addr()); 726 NonNull::new(ret).unwrap() 727 } 728 729 /// Lookup a function by index. 730 /// 731 /// # Panics 732 /// 733 /// Panics if `index` is out of bounds for this instance. 734 pub fn get_exported_func(&self, index: FuncIndex) -> ExportFunction { 735 let func_ref = self.get_func_ref(index).unwrap(); 736 ExportFunction { func_ref } 737 } 738 739 /// Lookup a table by index. 740 /// 741 /// # Panics 742 /// 743 /// Panics if `index` is out of bounds for this instance. 744 pub fn get_exported_table(&self, index: TableIndex) -> ExportTable { 745 let ty = self.env_module().tables[index]; 746 let (definition, vmctx, index) = 747 if let Some(def_index) = self.env_module().defined_table_index(index) { 748 (self.table_ptr(def_index), self.vmctx(), def_index) 749 } else { 750 let import = self.imported_table(index); 751 ( 752 import.from.as_non_null(), 753 import.vmctx.as_non_null(), 754 import.index, 755 ) 756 }; 757 ExportTable { 758 definition, 759 vmctx, 760 table: ty, 761 index, 762 } 763 } 764 765 /// Lookup a memory by index. 766 /// 767 /// # Panics 768 /// 769 /// Panics if `index` is out-of-bounds for this instance. 770 pub fn get_exported_memory(&self, index: MemoryIndex) -> ExportMemory { 771 let (definition, vmctx, def_index) = 772 if let Some(def_index) = self.env_module().defined_memory_index(index) { 773 (self.memory_ptr(def_index), self.vmctx(), def_index) 774 } else { 775 let import = self.imported_memory(index); 776 ( 777 import.from.as_non_null(), 778 import.vmctx.as_non_null(), 779 import.index, 780 ) 781 }; 782 ExportMemory { 783 definition, 784 vmctx, 785 memory: self.env_module().memories[index], 786 index: def_index, 787 } 788 } 789 790 fn get_exported_global(&self, index: GlobalIndex) -> ExportGlobal { 791 let global = self.env_module().globals[index]; 792 if let Some(def_index) = self.env_module().defined_global_index(index) { 793 ExportGlobal { 794 definition: self.global_ptr(def_index), 795 kind: ExportGlobalKind::Instance(self.vmctx(), def_index), 796 global, 797 } 798 } else { 799 ExportGlobal::from_vmimport(self.imported_global(index), global) 800 } 801 } 802 803 fn get_exported_tag(&self, index: TagIndex) -> ExportTag { 804 let tag = self.env_module().tags[index]; 805 let (vmctx, definition, index) = 806 if let Some(def_index) = self.env_module().defined_tag_index(index) { 807 (self.vmctx(), self.tag_ptr(def_index), def_index) 808 } else { 809 let import = self.imported_tag(index); 810 ( 811 import.vmctx.as_non_null(), 812 import.from.as_non_null(), 813 import.index, 814 ) 815 }; 816 ExportTag { 817 definition, 818 vmctx, 819 index, 820 tag, 821 } 822 } 823 824 /// Return an iterator over the exports of this instance. 825 /// 826 /// Specifically, it provides access to the key-value pairs, where the keys 827 /// are export names, and the values are export declarations which can be 828 /// resolved `lookup_by_declaration`. 829 pub fn exports(&self) -> wasmparser::collections::index_map::Iter<'_, String, EntityIndex> { 830 self.env_module().exports.iter() 831 } 832 833 /// Return the table index for the given `VMTableDefinition`. 834 pub unsafe fn table_index(&self, table: &VMTableDefinition) -> DefinedTableIndex { 835 let index = DefinedTableIndex::new( 836 usize::try_from( 837 (table as *const VMTableDefinition) 838 .offset_from(self.table_ptr(DefinedTableIndex::new(0)).as_ptr()), 839 ) 840 .unwrap(), 841 ); 842 assert!(index.index() < self.tables.len()); 843 index 844 } 845 846 /// Get the given memory's page size, in bytes. 847 pub(crate) fn memory_page_size(&self, index: MemoryIndex) -> usize { 848 usize::try_from(self.env_module().memories[index].page_size()).unwrap() 849 } 850 851 /// Grow memory by the specified amount of pages. 852 /// 853 /// Returns `None` if memory can't be grown by the specified amount 854 /// of pages. Returns `Some` with the old size in bytes if growth was 855 /// successful. 856 pub(crate) fn memory_grow( 857 self: Pin<&mut Self>, 858 store: &mut dyn VMStore, 859 index: MemoryIndex, 860 delta: u64, 861 ) -> Result<Option<usize>, Error> { 862 match self.env_module().defined_memory_index(index) { 863 Some(idx) => self.defined_memory_grow(store, idx, delta), 864 None => { 865 let import = self.imported_memory(index); 866 unsafe { 867 Instance::from_vmctx(import.vmctx.as_non_null(), |i| { 868 i.defined_memory_grow(store, import.index, delta) 869 }) 870 } 871 } 872 } 873 } 874 875 fn defined_memory_grow( 876 mut self: Pin<&mut Self>, 877 store: &mut dyn VMStore, 878 idx: DefinedMemoryIndex, 879 delta: u64, 880 ) -> Result<Option<usize>, Error> { 881 let memory = &mut self.as_mut().memories_mut()[idx].1; 882 883 let result = unsafe { memory.grow(delta, Some(store)) }; 884 885 // Update the state used by a non-shared Wasm memory in case the base 886 // pointer and/or the length changed. 887 if memory.as_shared_memory().is_none() { 888 let vmmemory = memory.vmmemory(); 889 self.set_memory(idx, vmmemory); 890 } 891 892 result 893 } 894 895 pub(crate) fn table_element_type( 896 self: Pin<&mut Self>, 897 table_index: TableIndex, 898 ) -> TableElementType { 899 unsafe { (*self.get_table(table_index)).element_type() } 900 } 901 902 /// Grow table by the specified amount of elements, filling them with 903 /// `init_value`. 904 /// 905 /// Returns `None` if table can't be grown by the specified amount of 906 /// elements, or if `init_value` is the wrong type of table element. 907 pub(crate) fn table_grow( 908 self: Pin<&mut Self>, 909 store: &mut dyn VMStore, 910 table_index: TableIndex, 911 delta: u64, 912 init_value: TableElement, 913 ) -> Result<Option<usize>, Error> { 914 self.with_defined_table_index_and_instance(table_index, |i, instance| { 915 instance.defined_table_grow(store, i, delta, init_value) 916 }) 917 } 918 919 fn defined_table_grow( 920 mut self: Pin<&mut Self>, 921 store: &mut dyn VMStore, 922 table_index: DefinedTableIndex, 923 delta: u64, 924 init_value: TableElement, 925 ) -> Result<Option<usize>, Error> { 926 let table = &mut self 927 .as_mut() 928 .tables_mut() 929 .get_mut(table_index) 930 .unwrap_or_else(|| panic!("no table for index {}", table_index.index())) 931 .1; 932 933 let result = unsafe { table.grow(delta, init_value, store) }; 934 935 // Keep the `VMContext` pointers used by compiled Wasm code up to 936 // date. 937 let element = table.vmtable(); 938 self.set_table(table_index, element); 939 940 result 941 } 942 943 fn alloc_layout(offsets: &VMOffsets<HostPtr>) -> Layout { 944 let size = mem::size_of::<Self>() 945 .checked_add(usize::try_from(offsets.size_of_vmctx()).unwrap()) 946 .unwrap(); 947 let align = mem::align_of::<Self>(); 948 Layout::from_size_align(size, align).unwrap() 949 } 950 951 fn type_ids_array(&self) -> NonNull<VmPtr<VMSharedTypeIndex>> { 952 unsafe { self.vmctx_plus_offset_raw(self.offsets().ptr.vmctx_type_ids_array()) } 953 } 954 955 /// Construct a new VMFuncRef for the given function 956 /// (imported or defined in this module) and store into the given 957 /// location. Used during lazy initialization. 958 /// 959 /// Note that our current lazy-init scheme actually calls this every 960 /// time the funcref pointer is fetched; this turns out to be better 961 /// than tracking state related to whether it's been initialized 962 /// before, because resetting that state on (re)instantiation is 963 /// very expensive if there are many funcrefs. 964 fn construct_func_ref( 965 &self, 966 index: FuncIndex, 967 type_index: VMSharedTypeIndex, 968 into: *mut VMFuncRef, 969 ) { 970 let func_ref = if let Some(def_index) = self.env_module().defined_func_index(index) { 971 VMFuncRef { 972 array_call: self 973 .runtime_info 974 .array_to_wasm_trampoline(def_index) 975 .expect("should have array-to-Wasm trampoline for escaping function") 976 .into(), 977 wasm_call: Some(self.runtime_info.function(def_index).into()), 978 vmctx: VMOpaqueContext::from_vmcontext(self.vmctx()).into(), 979 type_index, 980 } 981 } else { 982 let import = self.imported_function(index); 983 VMFuncRef { 984 array_call: import.array_call, 985 wasm_call: Some(import.wasm_call), 986 vmctx: import.vmctx, 987 type_index, 988 } 989 }; 990 991 // Safety: we have a `&mut self`, so we have exclusive access 992 // to this Instance. 993 unsafe { 994 ptr::write(into, func_ref); 995 } 996 } 997 998 /// Get a `&VMFuncRef` for the given `FuncIndex`. 999 /// 1000 /// Returns `None` if the index is the reserved index value. 1001 /// 1002 /// The returned reference is a stable reference that won't be moved and can 1003 /// be passed into JIT code. 1004 pub(crate) fn get_func_ref(&self, index: FuncIndex) -> Option<NonNull<VMFuncRef>> { 1005 if index == FuncIndex::reserved_value() { 1006 return None; 1007 } 1008 1009 // Safety: we have a `&mut self`, so we have exclusive access 1010 // to this Instance. 1011 unsafe { 1012 // For now, we eagerly initialize an funcref struct in-place 1013 // whenever asked for a reference to it. This is mostly 1014 // fine, because in practice each funcref is unlikely to be 1015 // requested more than a few times: once-ish for funcref 1016 // tables used for call_indirect (the usual compilation 1017 // strategy places each function in the table at most once), 1018 // and once or a few times when fetching exports via API. 1019 // Note that for any case driven by table accesses, the lazy 1020 // table init behaves like a higher-level cache layer that 1021 // protects this initialization from happening multiple 1022 // times, via that particular table at least. 1023 // 1024 // When `ref.func` becomes more commonly used or if we 1025 // otherwise see a use-case where this becomes a hotpath, 1026 // we can reconsider by using some state to track 1027 // "uninitialized" explicitly, for example by zeroing the 1028 // funcrefs (perhaps together with other 1029 // zeroed-at-instantiate-time state) or using a separate 1030 // is-initialized bitmap. 1031 // 1032 // We arrived at this design because zeroing memory is 1033 // expensive, so it's better for instantiation performance 1034 // if we don't have to track "is-initialized" state at 1035 // all! 1036 let func = &self.env_module().functions[index]; 1037 let sig = func.signature.unwrap_engine_type_index(); 1038 let func_ref = self 1039 .vmctx_plus_offset_raw::<VMFuncRef>(self.offsets().vmctx_func_ref(func.func_ref)); 1040 self.construct_func_ref(index, sig, func_ref.as_ptr()); 1041 1042 Some(func_ref) 1043 } 1044 } 1045 1046 /// Get the passive elements segment at the given index. 1047 /// 1048 /// Returns an empty segment if the index is out of bounds or if the segment 1049 /// has been dropped. 1050 /// 1051 /// The `storage` parameter should always be `None`; it is a bit of a hack 1052 /// to work around lifetime issues. 1053 pub(crate) fn passive_element_segment<'a>( 1054 &self, 1055 storage: &'a mut Option<(Arc<wasmtime_environ::Module>, TableSegmentElements)>, 1056 elem_index: ElemIndex, 1057 ) -> &'a TableSegmentElements { 1058 debug_assert!(storage.is_none()); 1059 *storage = Some(( 1060 // TODO: this `clone()` shouldn't be necessary but is used for now to 1061 // inform `rustc` that the lifetime of the elements here are 1062 // disconnected from the lifetime of `self`. 1063 self.env_module().clone(), 1064 // NB: fall back to an expressions-based list of elements which 1065 // doesn't have static type information (as opposed to 1066 // `TableSegmentElements::Functions`) since we don't know what type 1067 // is needed in the caller's context. Let the type be inferred by 1068 // how they use the segment. 1069 TableSegmentElements::Expressions(Box::new([])), 1070 )); 1071 let (module, empty) = storage.as_ref().unwrap(); 1072 1073 match module.passive_elements_map.get(&elem_index) { 1074 Some(index) if !self.dropped_elements.contains(elem_index) => { 1075 &module.passive_elements[*index] 1076 } 1077 _ => empty, 1078 } 1079 } 1080 1081 /// The `table.init` operation: initializes a portion of a table with a 1082 /// passive element. 1083 /// 1084 /// # Errors 1085 /// 1086 /// Returns a `Trap` error when the range within the table is out of bounds 1087 /// or the range within the passive element is out of bounds. 1088 pub(crate) fn table_init( 1089 self: Pin<&mut Self>, 1090 store: &mut StoreOpaque, 1091 table_index: TableIndex, 1092 elem_index: ElemIndex, 1093 dst: u64, 1094 src: u64, 1095 len: u64, 1096 ) -> Result<(), Trap> { 1097 let mut storage = None; 1098 let elements = self.passive_element_segment(&mut storage, elem_index); 1099 let mut const_evaluator = ConstExprEvaluator::default(); 1100 Self::table_init_segment( 1101 store, 1102 self.id, 1103 &mut const_evaluator, 1104 table_index, 1105 elements, 1106 dst, 1107 src, 1108 len, 1109 ) 1110 } 1111 1112 pub(crate) fn table_init_segment( 1113 store: &mut StoreOpaque, 1114 id: InstanceId, 1115 const_evaluator: &mut ConstExprEvaluator, 1116 table_index: TableIndex, 1117 elements: &TableSegmentElements, 1118 dst: u64, 1119 src: u64, 1120 len: u64, 1121 ) -> Result<(), Trap> { 1122 // https://webassembly.github.io/bulk-memory-operations/core/exec/instructions.html#exec-table-init 1123 1124 let mut instance = store.instance_mut(id); 1125 let table = unsafe { &mut *instance.as_mut().get_table(table_index) }; 1126 let src = usize::try_from(src).map_err(|_| Trap::TableOutOfBounds)?; 1127 let len = usize::try_from(len).map_err(|_| Trap::TableOutOfBounds)?; 1128 let module = instance.env_module().clone(); 1129 1130 match elements { 1131 TableSegmentElements::Functions(funcs) => { 1132 let elements = funcs 1133 .get(src..) 1134 .and_then(|s| s.get(..len)) 1135 .ok_or(Trap::TableOutOfBounds)?; 1136 table.init_func(dst, elements.iter().map(|idx| instance.get_func_ref(*idx)))?; 1137 } 1138 TableSegmentElements::Expressions(exprs) => { 1139 let exprs = exprs 1140 .get(src..) 1141 .and_then(|s| s.get(..len)) 1142 .ok_or(Trap::TableOutOfBounds)?; 1143 let top = module.tables[table_index].ref_type.heap_type.top(); 1144 let mut context = ConstEvalContext::new(id); 1145 match top { 1146 WasmHeapTopType::Extern => table.init_gc_refs( 1147 dst, 1148 exprs.iter().map(|expr| unsafe { 1149 let raw = const_evaluator 1150 .eval(store, &mut context, expr) 1151 .expect("const expr should be valid"); 1152 VMGcRef::from_raw_u32(raw.get_externref()) 1153 }), 1154 )?, 1155 WasmHeapTopType::Any => table.init_gc_refs( 1156 dst, 1157 exprs.iter().map(|expr| unsafe { 1158 let raw = const_evaluator 1159 .eval(store, &mut context, expr) 1160 .expect("const expr should be valid"); 1161 VMGcRef::from_raw_u32(raw.get_anyref()) 1162 }), 1163 )?, 1164 WasmHeapTopType::Func => table.init_func( 1165 dst, 1166 exprs.iter().map(|expr| unsafe { 1167 NonNull::new( 1168 const_evaluator 1169 .eval(store, &mut context, expr) 1170 .expect("const expr should be valid") 1171 .get_funcref() 1172 .cast(), 1173 ) 1174 }), 1175 )?, 1176 WasmHeapTopType::Cont => todo!(), // FIXME: #10248 stack switching support. 1177 } 1178 } 1179 } 1180 1181 Ok(()) 1182 } 1183 1184 /// Drop an element. 1185 pub(crate) fn elem_drop(self: Pin<&mut Self>, elem_index: ElemIndex) { 1186 // https://webassembly.github.io/reference-types/core/exec/instructions.html#exec-elem-drop 1187 1188 self.dropped_elements_mut().insert(elem_index); 1189 1190 // Note that we don't check that we actually removed a segment because 1191 // dropping a non-passive segment is a no-op (not a trap). 1192 } 1193 1194 /// Get a locally-defined memory. 1195 pub fn get_defined_memory(self: Pin<&mut Self>, index: DefinedMemoryIndex) -> *mut Memory { 1196 // SAFETY: the `unsafe` here is projecting from `*mut (A, B)` to 1197 // `*mut A`, which should be a safe operation to do. 1198 unsafe { &raw mut (*self.memories_mut().get_raw_mut(index).unwrap()).1 } 1199 } 1200 1201 /// Do a `memory.copy` 1202 /// 1203 /// # Errors 1204 /// 1205 /// Returns a `Trap` error when the source or destination ranges are out of 1206 /// bounds. 1207 pub(crate) fn memory_copy( 1208 self: Pin<&mut Self>, 1209 dst_index: MemoryIndex, 1210 dst: u64, 1211 src_index: MemoryIndex, 1212 src: u64, 1213 len: u64, 1214 ) -> Result<(), Trap> { 1215 // https://webassembly.github.io/reference-types/core/exec/instructions.html#exec-memory-copy 1216 1217 let src_mem = self.get_memory(src_index); 1218 let dst_mem = self.get_memory(dst_index); 1219 1220 let src = self.validate_inbounds(src_mem.current_length(), src, len)?; 1221 let dst = self.validate_inbounds(dst_mem.current_length(), dst, len)?; 1222 let len = usize::try_from(len).unwrap(); 1223 1224 // Bounds and casts are checked above, by this point we know that 1225 // everything is safe. 1226 unsafe { 1227 let dst = dst_mem.base.as_ptr().add(dst); 1228 let src = src_mem.base.as_ptr().add(src); 1229 // FIXME audit whether this is safe in the presence of shared memory 1230 // (https://github.com/bytecodealliance/wasmtime/issues/4203). 1231 ptr::copy(src, dst, len); 1232 } 1233 1234 Ok(()) 1235 } 1236 1237 fn validate_inbounds(&self, max: usize, ptr: u64, len: u64) -> Result<usize, Trap> { 1238 let oob = || Trap::MemoryOutOfBounds; 1239 let end = ptr 1240 .checked_add(len) 1241 .and_then(|i| usize::try_from(i).ok()) 1242 .ok_or_else(oob)?; 1243 if end > max { 1244 Err(oob()) 1245 } else { 1246 Ok(ptr.try_into().unwrap()) 1247 } 1248 } 1249 1250 /// Perform the `memory.fill` operation on a locally defined memory. 1251 /// 1252 /// # Errors 1253 /// 1254 /// Returns a `Trap` error if the memory range is out of bounds. 1255 pub(crate) fn memory_fill( 1256 self: Pin<&mut Self>, 1257 memory_index: MemoryIndex, 1258 dst: u64, 1259 val: u8, 1260 len: u64, 1261 ) -> Result<(), Trap> { 1262 let memory = self.get_memory(memory_index); 1263 let dst = self.validate_inbounds(memory.current_length(), dst, len)?; 1264 let len = usize::try_from(len).unwrap(); 1265 1266 // Bounds and casts are checked above, by this point we know that 1267 // everything is safe. 1268 unsafe { 1269 let dst = memory.base.as_ptr().add(dst); 1270 // FIXME audit whether this is safe in the presence of shared memory 1271 // (https://github.com/bytecodealliance/wasmtime/issues/4203). 1272 ptr::write_bytes(dst, val, len); 1273 } 1274 1275 Ok(()) 1276 } 1277 1278 /// Get the internal storage range of a particular Wasm data segment. 1279 pub(crate) fn wasm_data_range(&self, index: DataIndex) -> Range<u32> { 1280 match self.env_module().passive_data_map.get(&index) { 1281 Some(range) if !self.dropped_data.contains(index) => range.clone(), 1282 _ => 0..0, 1283 } 1284 } 1285 1286 /// Given an internal storage range of a Wasm data segment (or subset of a 1287 /// Wasm data segment), get the data's raw bytes. 1288 pub(crate) fn wasm_data(&self, range: Range<u32>) -> &[u8] { 1289 let start = usize::try_from(range.start).unwrap(); 1290 let end = usize::try_from(range.end).unwrap(); 1291 &self.runtime_info.wasm_data()[start..end] 1292 } 1293 1294 /// Performs the `memory.init` operation. 1295 /// 1296 /// # Errors 1297 /// 1298 /// Returns a `Trap` error if the destination range is out of this module's 1299 /// memory's bounds or if the source range is outside the data segment's 1300 /// bounds. 1301 pub(crate) fn memory_init( 1302 self: Pin<&mut Self>, 1303 memory_index: MemoryIndex, 1304 data_index: DataIndex, 1305 dst: u64, 1306 src: u32, 1307 len: u32, 1308 ) -> Result<(), Trap> { 1309 let range = self.wasm_data_range(data_index); 1310 self.memory_init_segment(memory_index, range, dst, src, len) 1311 } 1312 1313 pub(crate) fn memory_init_segment( 1314 self: Pin<&mut Self>, 1315 memory_index: MemoryIndex, 1316 range: Range<u32>, 1317 dst: u64, 1318 src: u32, 1319 len: u32, 1320 ) -> Result<(), Trap> { 1321 // https://webassembly.github.io/bulk-memory-operations/core/exec/instructions.html#exec-memory-init 1322 1323 let memory = self.get_memory(memory_index); 1324 let data = self.wasm_data(range); 1325 let dst = self.validate_inbounds(memory.current_length(), dst, len.into())?; 1326 let src = self.validate_inbounds(data.len(), src.into(), len.into())?; 1327 let len = len as usize; 1328 1329 unsafe { 1330 let src_start = data.as_ptr().add(src); 1331 let dst_start = memory.base.as_ptr().add(dst); 1332 // FIXME audit whether this is safe in the presence of shared memory 1333 // (https://github.com/bytecodealliance/wasmtime/issues/4203). 1334 ptr::copy_nonoverlapping(src_start, dst_start, len); 1335 } 1336 1337 Ok(()) 1338 } 1339 1340 /// Drop the given data segment, truncating its length to zero. 1341 pub(crate) fn data_drop(self: Pin<&mut Self>, data_index: DataIndex) { 1342 self.dropped_data_mut().insert(data_index); 1343 1344 // Note that we don't check that we actually removed a segment because 1345 // dropping a non-passive segment is a no-op (not a trap). 1346 } 1347 1348 /// Get a table by index regardless of whether it is locally-defined 1349 /// or an imported, foreign table. Ensure that the given range of 1350 /// elements in the table is lazily initialized. We define this 1351 /// operation all-in-one for safety, to ensure the lazy-init 1352 /// happens. 1353 /// 1354 /// Takes an `Iterator` for the index-range to lazy-initialize, 1355 /// for flexibility. This can be a range, single item, or empty 1356 /// sequence, for example. The iterator should return indices in 1357 /// increasing order, so that the break-at-out-of-bounds behavior 1358 /// works correctly. 1359 pub(crate) fn get_table_with_lazy_init( 1360 self: Pin<&mut Self>, 1361 table_index: TableIndex, 1362 range: impl Iterator<Item = u64>, 1363 ) -> *mut Table { 1364 self.with_defined_table_index_and_instance(table_index, |idx, instance| { 1365 instance.get_defined_table_with_lazy_init(idx, range) 1366 }) 1367 } 1368 1369 /// Gets the raw runtime table data structure owned by this instance 1370 /// given the provided `idx`. 1371 /// 1372 /// The `range` specified is eagerly initialized for funcref tables. 1373 pub fn get_defined_table_with_lazy_init( 1374 mut self: Pin<&mut Self>, 1375 idx: DefinedTableIndex, 1376 range: impl Iterator<Item = u64>, 1377 ) -> *mut Table { 1378 let elt_ty = self.tables[idx].1.element_type(); 1379 1380 if elt_ty == TableElementType::Func { 1381 for i in range { 1382 let value = match self.tables[idx].1.get(None, i) { 1383 Some(value) => value, 1384 None => { 1385 // Out-of-bounds; caller will handle by likely 1386 // throwing a trap. No work to do to lazy-init 1387 // beyond the end. 1388 break; 1389 } 1390 }; 1391 1392 if !value.is_uninit() { 1393 continue; 1394 } 1395 1396 // The table element `i` is uninitialized and is now being 1397 // initialized. This must imply that a `precompiled` list of 1398 // function indices is available for this table. The precompiled 1399 // list is extracted and then it is consulted with `i` to 1400 // determine the function that is going to be initialized. Note 1401 // that `i` may be outside the limits of the static 1402 // initialization so it's a fallible `get` instead of an index. 1403 let module = self.env_module(); 1404 let precomputed = match &module.table_initialization.initial_values[idx] { 1405 TableInitialValue::Null { precomputed } => precomputed, 1406 TableInitialValue::Expr(_) => unreachable!(), 1407 }; 1408 // Panicking here helps catch bugs rather than silently truncating by accident. 1409 let func_index = precomputed.get(usize::try_from(i).unwrap()).cloned(); 1410 let func_ref = func_index.and_then(|func_index| self.get_func_ref(func_index)); 1411 self.as_mut().tables_mut()[idx] 1412 .1 1413 .set(i, TableElement::FuncRef(func_ref)) 1414 .expect("Table type should match and index should be in-bounds"); 1415 } 1416 } 1417 1418 // SAFETY: the `unsafe` here is projecting from `*mut (A, B)` to 1419 // `*mut A`, which should be a safe operation to do. 1420 unsafe { &raw mut (*self.tables_mut().get_raw_mut(idx).unwrap()).1 } 1421 } 1422 1423 /// Get a table by index regardless of whether it is locally-defined or an 1424 /// imported, foreign table. 1425 pub(crate) fn get_table(self: Pin<&mut Self>, table_index: TableIndex) -> *mut Table { 1426 self.with_defined_table_index_and_instance(table_index, |idx, instance| unsafe { 1427 // SAFETY: the `unsafe` here is projecting from `*mut (A, B)` to 1428 // `*mut A`, which should be a safe operation to do. 1429 &raw mut (*instance.tables_mut().get_raw_mut(idx).unwrap()).1 1430 }) 1431 } 1432 1433 /// Get a locally-defined table. 1434 pub(crate) fn get_defined_table(self: Pin<&mut Self>, index: DefinedTableIndex) -> *mut Table { 1435 // SAFETY: the `unsafe` here is projecting from `*mut (A, B)` to 1436 // `*mut A`, which should be a safe operation to do. 1437 unsafe { &raw mut (*self.tables_mut().get_raw_mut(index).unwrap()).1 } 1438 } 1439 1440 pub(crate) fn with_defined_table_index_and_instance<R>( 1441 self: Pin<&mut Self>, 1442 index: TableIndex, 1443 f: impl FnOnce(DefinedTableIndex, Pin<&mut Instance>) -> R, 1444 ) -> R { 1445 if let Some(defined_table_index) = self.env_module().defined_table_index(index) { 1446 f(defined_table_index, self) 1447 } else { 1448 let import = self.imported_table(index); 1449 unsafe { 1450 Instance::from_vmctx(import.vmctx.as_non_null(), |foreign_instance| { 1451 let foreign_table_def = import.from.as_ptr(); 1452 let foreign_table_index = foreign_instance.table_index(&*foreign_table_def); 1453 f(foreign_table_index, foreign_instance) 1454 }) 1455 } 1456 } 1457 } 1458 1459 /// Initialize the VMContext data associated with this Instance. 1460 /// 1461 /// The `VMContext` memory is assumed to be uninitialized; any field 1462 /// that we need in a certain state will be explicitly written by this 1463 /// function. 1464 unsafe fn initialize_vmctx( 1465 mut self: Pin<&mut Self>, 1466 module: &Module, 1467 offsets: &VMOffsets<HostPtr>, 1468 store: StorePtr, 1469 imports: Imports, 1470 ) { 1471 assert!(ptr::eq(module, self.env_module().as_ref())); 1472 1473 self.vmctx_plus_offset_raw::<u32>(offsets.ptr.vmctx_magic()) 1474 .write(VMCONTEXT_MAGIC); 1475 self.as_mut().set_store(store.as_raw()); 1476 1477 // Initialize shared types 1478 let types = NonNull::from(self.runtime_info.type_ids()); 1479 self.type_ids_array().write(types.cast().into()); 1480 1481 // Initialize the built-in functions 1482 static BUILTINS: VMBuiltinFunctionsArray = VMBuiltinFunctionsArray::INIT; 1483 let ptr = BUILTINS.expose_provenance(); 1484 self.vmctx_plus_offset_raw(offsets.ptr.vmctx_builtin_functions()) 1485 .write(VmPtr::from(ptr)); 1486 1487 // Initialize the imports 1488 debug_assert_eq!(imports.functions.len(), module.num_imported_funcs); 1489 ptr::copy_nonoverlapping( 1490 imports.functions.as_ptr(), 1491 self.vmctx_plus_offset_raw(offsets.vmctx_imported_functions_begin()) 1492 .as_ptr(), 1493 imports.functions.len(), 1494 ); 1495 debug_assert_eq!(imports.tables.len(), module.num_imported_tables); 1496 ptr::copy_nonoverlapping( 1497 imports.tables.as_ptr(), 1498 self.vmctx_plus_offset_raw(offsets.vmctx_imported_tables_begin()) 1499 .as_ptr(), 1500 imports.tables.len(), 1501 ); 1502 debug_assert_eq!(imports.memories.len(), module.num_imported_memories); 1503 ptr::copy_nonoverlapping( 1504 imports.memories.as_ptr(), 1505 self.vmctx_plus_offset_raw(offsets.vmctx_imported_memories_begin()) 1506 .as_ptr(), 1507 imports.memories.len(), 1508 ); 1509 debug_assert_eq!(imports.globals.len(), module.num_imported_globals); 1510 ptr::copy_nonoverlapping( 1511 imports.globals.as_ptr(), 1512 self.vmctx_plus_offset_raw(offsets.vmctx_imported_globals_begin()) 1513 .as_ptr(), 1514 imports.globals.len(), 1515 ); 1516 1517 debug_assert_eq!(imports.tags.len(), module.num_imported_tags); 1518 ptr::copy_nonoverlapping( 1519 imports.tags.as_ptr(), 1520 self.vmctx_plus_offset_raw(offsets.vmctx_imported_tags_begin()) 1521 .as_ptr(), 1522 imports.tags.len(), 1523 ); 1524 1525 // N.B.: there is no need to initialize the funcrefs array because we 1526 // eagerly construct each element in it whenever asked for a reference 1527 // to that element. In other words, there is no state needed to track 1528 // the lazy-init, so we don't need to initialize any state now. 1529 1530 // Initialize the defined tables 1531 let mut ptr = self.vmctx_plus_offset_raw(offsets.vmctx_tables_begin()); 1532 let tables = self.as_mut().tables_mut(); 1533 for i in 0..module.num_defined_tables() { 1534 ptr.write(tables[DefinedTableIndex::new(i)].1.vmtable()); 1535 ptr = ptr.add(1); 1536 } 1537 1538 // Initialize the defined memories. This fills in both the 1539 // `defined_memories` table and the `owned_memories` table at the same 1540 // time. Entries in `defined_memories` hold a pointer to a definition 1541 // (all memories) whereas the `owned_memories` hold the actual 1542 // definitions of memories owned (not shared) in the module. 1543 let mut ptr = self.vmctx_plus_offset_raw(offsets.vmctx_memories_begin()); 1544 let mut owned_ptr = self.vmctx_plus_offset_raw(offsets.vmctx_owned_memories_begin()); 1545 let memories = self.as_mut().memories_mut(); 1546 for i in 0..module.num_defined_memories() { 1547 let defined_memory_index = DefinedMemoryIndex::new(i); 1548 let memory_index = module.memory_index(defined_memory_index); 1549 if module.memories[memory_index].shared { 1550 let def_ptr = memories[defined_memory_index] 1551 .1 1552 .as_shared_memory() 1553 .unwrap() 1554 .vmmemory_ptr(); 1555 ptr.write(VmPtr::from(def_ptr)); 1556 } else { 1557 owned_ptr.write(memories[defined_memory_index].1.vmmemory()); 1558 ptr.write(VmPtr::from(owned_ptr)); 1559 owned_ptr = owned_ptr.add(1); 1560 } 1561 ptr = ptr.add(1); 1562 } 1563 1564 // Zero-initialize the globals so that nothing is uninitialized memory 1565 // after this function returns. The globals are actually initialized 1566 // with their const expression initializers after the instance is fully 1567 // allocated. 1568 for (index, _init) in module.global_initializers.iter() { 1569 self.global_ptr(index).write(VMGlobalDefinition::new()); 1570 } 1571 1572 // Initialize the defined tags 1573 let mut ptr = self.vmctx_plus_offset_raw(offsets.vmctx_tags_begin()); 1574 for i in 0..module.num_defined_tags() { 1575 let defined_index = DefinedTagIndex::new(i); 1576 let tag_index = module.tag_index(defined_index); 1577 let tag = module.tags[tag_index]; 1578 ptr.write(VMTagDefinition::new( 1579 tag.signature.unwrap_engine_type_index(), 1580 )); 1581 ptr = ptr.add(1); 1582 } 1583 } 1584 1585 /// Attempts to convert from the host `addr` specified to a WebAssembly 1586 /// based address recorded in `WasmFault`. 1587 /// 1588 /// This method will check all linear memories that this instance contains 1589 /// to see if any of them contain `addr`. If one does then `Some` is 1590 /// returned with metadata about the wasm fault. Otherwise `None` is 1591 /// returned and `addr` doesn't belong to this instance. 1592 pub fn wasm_fault(&self, addr: usize) -> Option<WasmFault> { 1593 let mut fault = None; 1594 for (_, (_, memory)) in self.memories.iter() { 1595 let accessible = memory.wasm_accessible(); 1596 if accessible.start <= addr && addr < accessible.end { 1597 // All linear memories should be disjoint so assert that no 1598 // prior fault has been found. 1599 assert!(fault.is_none()); 1600 fault = Some(WasmFault { 1601 memory_size: memory.byte_size(), 1602 wasm_address: u64::try_from(addr - accessible.start).unwrap(), 1603 }); 1604 } 1605 } 1606 fault 1607 } 1608 1609 /// Returns the id, within this instance's store, that it's assigned. 1610 pub fn id(&self) -> InstanceId { 1611 self.id 1612 } 1613 1614 /// Get all memories within this instance. 1615 /// 1616 /// Returns both import and defined memories. 1617 /// 1618 /// Returns both exported and non-exported memories. 1619 /// 1620 /// Gives access to the full memories space. 1621 pub fn all_memories<'a>( 1622 &'a self, 1623 ) -> impl ExactSizeIterator<Item = (MemoryIndex, ExportMemory)> + 'a { 1624 let indices = (0..self.env_module().memories.len()) 1625 .map(|i| MemoryIndex::new(i)) 1626 .collect::<Vec<_>>(); 1627 indices 1628 .into_iter() 1629 .map(|i| (i, self.get_exported_memory(i))) 1630 } 1631 1632 /// Return the memories defined in this instance (not imported). 1633 pub fn defined_memories<'a>(&'a self) -> impl ExactSizeIterator<Item = ExportMemory> + 'a { 1634 let num_imported = self.env_module().num_imported_memories; 1635 self.all_memories() 1636 .skip(num_imported) 1637 .map(|(_i, memory)| memory) 1638 } 1639 1640 /// Lookup an item with the given index. 1641 /// 1642 /// # Panics 1643 /// 1644 /// Panics if `export` is not valid for this instance. 1645 pub fn get_export_by_index(&self, export: EntityIndex) -> Export { 1646 match export { 1647 EntityIndex::Function(i) => Export::Function(self.get_exported_func(i)), 1648 EntityIndex::Global(i) => Export::Global(self.get_exported_global(i)), 1649 EntityIndex::Table(i) => Export::Table(self.get_exported_table(i)), 1650 EntityIndex::Memory(i) => Export::Memory(self.get_exported_memory(i)), 1651 EntityIndex::Tag(i) => Export::Tag(self.get_exported_tag(i)), 1652 } 1653 } 1654 1655 fn store_mut(self: Pin<&mut Self>) -> &mut Option<VMStoreRawPtr> { 1656 // SAFETY: this is a pin-projection to get a mutable reference to an 1657 // internal field and is safe so long as the `&mut Self` temporarily 1658 // created is not overwritten, which it isn't here. 1659 unsafe { &mut self.get_unchecked_mut().store } 1660 } 1661 1662 fn dropped_elements_mut(self: Pin<&mut Self>) -> &mut EntitySet<ElemIndex> { 1663 // SAFETY: see `store_mut` above. 1664 unsafe { &mut self.get_unchecked_mut().dropped_elements } 1665 } 1666 1667 fn dropped_data_mut(self: Pin<&mut Self>) -> &mut EntitySet<DataIndex> { 1668 // SAFETY: see `store_mut` above. 1669 unsafe { &mut self.get_unchecked_mut().dropped_data } 1670 } 1671 1672 fn memories_mut( 1673 self: Pin<&mut Self>, 1674 ) -> &mut PrimaryMap<DefinedMemoryIndex, (MemoryAllocationIndex, Memory)> { 1675 // SAFETY: see `store_mut` above. 1676 unsafe { &mut self.get_unchecked_mut().memories } 1677 } 1678 1679 fn tables_mut( 1680 self: Pin<&mut Self>, 1681 ) -> &mut PrimaryMap<DefinedTableIndex, (TableAllocationIndex, Table)> { 1682 // SAFETY: see `store_mut` above. 1683 unsafe { &mut self.get_unchecked_mut().tables } 1684 } 1685 1686 #[cfg(feature = "wmemcheck")] 1687 pub(super) fn wmemcheck_state_mut(self: Pin<&mut Self>) -> &mut Option<Wmemcheck> { 1688 // SAFETY: see `store_mut` above. 1689 unsafe { &mut self.get_unchecked_mut().wmemcheck_state } 1690 } 1691 } 1692 1693 /// A handle holding an `Instance` of a WebAssembly module. 1694 /// 1695 /// This structure is an owning handle of the `instance` contained internally. 1696 /// When this value goes out of scope it will deallocate the `Instance` and all 1697 /// memory associated with it. 1698 /// 1699 /// Note that this lives within a `StoreOpaque` on a list of instances that a 1700 /// store is keeping alive. 1701 #[derive(Debug)] 1702 pub struct InstanceHandle { 1703 /// The raw pointer to the instance that was allocated. 1704 /// 1705 /// Note that this is not equivalent to `Box<Instance>` because the 1706 /// allocation here has a `VMContext` trailing after it. Thus the custom 1707 /// destructor to invoke the `dealloc` function with the appropriate 1708 /// layout. 1709 instance: SendSyncPtr<Instance>, 1710 } 1711 1712 impl InstanceHandle { 1713 /// Gets the raw underlying `&Instance` from this handle. 1714 pub fn get(&self) -> &Instance { 1715 // SAFETY: this is an owned instance handle that retains exclusive 1716 // ownership of the `Instance` inside. With `&self` given we know 1717 // this pointer is valid valid and the returned lifetime is connected 1718 // to `self` so that should also be valid. 1719 unsafe { self.instance.as_non_null().as_ref() } 1720 } 1721 1722 /// Same as [`Self::get`] except for mutability. 1723 pub fn get_mut(&mut self) -> Pin<&mut Instance> { 1724 // SAFETY: The lifetime concerns here are the same as `get` above. 1725 // Otherwise `new_unchecked` is used here to uphold the contract that 1726 // instances are always pinned in memory. 1727 unsafe { Pin::new_unchecked(self.instance.as_non_null().as_mut()) } 1728 } 1729 } 1730 1731 impl Drop for InstanceHandle { 1732 fn drop(&mut self) { 1733 unsafe { 1734 let layout = Instance::alloc_layout(self.get().offsets()); 1735 ptr::drop_in_place(self.instance.as_ptr()); 1736 alloc::alloc::dealloc(self.instance.as_ptr().cast(), layout); 1737 } 1738 } 1739 } 1740