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