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