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