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