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