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