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