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