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