wasmtime/runtime/externals/table.rs
1use crate::prelude::*;
2use crate::runtime::vm::{self, GcStore, TableElementType, VMFuncRef, VMGcRef, VMStore};
3use crate::store::{AutoAssertNoGc, StoreInstanceId, StoreOpaque, StoreResourceLimiter};
4use crate::trampoline::generate_table_export;
5use crate::{
6 AnyRef, AsContext, AsContextMut, ExnRef, ExternRef, Func, HeapTopType, Ref, RefType,
7 StoreContextMut, TableType, Trap, Unrooted,
8};
9use core::iter;
10use core::ptr::NonNull;
11use wasmtime_environ::DefinedTableIndex;
12
13/// A WebAssembly `table`, or an array of values.
14///
15/// Like [`Memory`][crate::Memory] a table is an indexed array of values, but
16/// unlike [`Memory`][crate::Memory] it's an array of WebAssembly reference type
17/// values rather than bytes. One of the most common usages of a table is a
18/// function table for wasm modules (a `funcref` table), where each element has
19/// the `ValType::FuncRef` type.
20///
21/// A [`Table`] "belongs" to the store that it was originally created within
22/// (either via [`Table::new`] or via instantiating a
23/// [`Module`](crate::Module)). Operations on a [`Table`] only work with the
24/// store it belongs to, and if another store is passed in by accident then
25/// methods will panic.
26#[derive(Copy, Clone, Debug)]
27#[repr(C)] // here for the C API
28pub struct Table {
29 instance: StoreInstanceId,
30 index: DefinedTableIndex,
31}
32
33// Double-check that the C representation in `extern.h` matches our in-Rust
34// representation here in terms of size/alignment/etc.
35const _: () = {
36 #[repr(C)]
37 struct Tmp(u64, u32);
38 #[repr(C)]
39 struct C(Tmp, u32);
40 assert!(core::mem::size_of::<C>() == core::mem::size_of::<Table>());
41 assert!(core::mem::align_of::<C>() == core::mem::align_of::<Table>());
42 assert!(core::mem::offset_of!(Table, instance) == 0);
43};
44
45impl Table {
46 /// Creates a new [`Table`] with the given parameters.
47 ///
48 /// * `store` - the owner of the resulting [`Table`]
49 /// * `ty` - the type of this table, containing both the element type as
50 /// well as the initial size and maximum size, if any.
51 /// * `init` - the initial value to fill all table entries with, if the
52 /// table starts with an initial size.
53 ///
54 /// # Errors
55 ///
56 /// Returns an error if `init` does not match the element type of the table,
57 /// or if `init` does not belong to the `store` provided.
58 ///
59 /// Returns an error if the element type of `ty` was not created with the
60 /// same [`Engine`](crate::Engine) as `store`.
61 ///
62 /// This function will also return an error when used with a
63 /// [`Store`](`crate::Store`) which has a
64 /// [`ResourceLimiterAsync`](`crate::ResourceLimiterAsync`) (see also:
65 /// [`Store::limiter_async`](`crate::Store::limiter_async`). When using an
66 /// async resource limiter, use [`Table::new_async`] instead.
67 ///
68 /// This function will return an [`OutOfMemory`][crate::OutOfMemory] error when
69 /// memory allocation fails. See the `OutOfMemory` type's documentation for
70 /// details on Wasmtime's out-of-memory handling.
71 ///
72 /// # Examples
73 ///
74 /// ```
75 /// # use wasmtime::*;
76 /// # fn main() -> Result<()> {
77 /// let engine = Engine::default();
78 /// let mut store = Store::new(&engine, ());
79 ///
80 /// let ty = TableType::new(RefType::FUNCREF, 2, None)?;
81 /// let table = Table::new(&mut store, ty, Ref::Func(None))?;
82 ///
83 /// let module = Module::new(
84 /// &engine,
85 /// "(module
86 /// (table (import \"\" \"\") 2 funcref)
87 /// (func $f (result i32)
88 /// i32.const 10)
89 /// (elem (i32.const 0) $f)
90 /// )"
91 /// )?;
92 ///
93 /// let instance = Instance::new(&mut store, &module, &[table.into()])?;
94 /// // ...
95 /// # Ok(())
96 /// # }
97 /// ```
98 pub fn new(mut store: impl AsContextMut, ty: TableType, init: Ref) -> Result<Table> {
99 let (mut limiter, store) = store
100 .as_context_mut()
101 .0
102 .validate_sync_resource_limiter_and_store_opaque()?;
103 vm::assert_ready(Table::_new(store, limiter.as_mut(), ty, init))
104 }
105
106 /// Async variant of [`Table::new`].
107 ///
108 /// You must use this variant with [`Store`](`crate::Store`)s which have a
109 /// [`ResourceLimiterAsync`](`crate::ResourceLimiterAsync`).
110 ///
111 /// # Errors
112 ///
113 /// Returns an error if the element type of `ty` was not created with the
114 /// same [`Engine`](crate::Engine) as `store`.
115 ///
116 /// This function will return an [`OutOfMemory`][crate::OutOfMemory] error when
117 /// memory allocation fails. See the `OutOfMemory` type's documentation for
118 /// details on Wasmtime's out-of-memory handling.
119 #[cfg(feature = "async")]
120 pub async fn new_async(
121 mut store: impl AsContextMut,
122 ty: TableType,
123 init: Ref,
124 ) -> Result<Table> {
125 let (mut limiter, store) = store.as_context_mut().0.resource_limiter_and_store_opaque();
126 Table::_new(store, limiter.as_mut(), ty, init).await
127 }
128
129 async fn _new(
130 store: &mut StoreOpaque,
131 limiter: Option<&mut StoreResourceLimiter<'_>>,
132 ty: TableType,
133 init: Ref,
134 ) -> Result<Table> {
135 init.validate_rooted()?;
136 init.ensure_matches_ty(store, ty.element())
137 .context("type mismatch: value does not match table element type")?;
138 store.bump_table_count()?;
139 let table = generate_table_export(store, limiter, &ty).await?;
140
141 // Tables are always allocated as all zeroes, so skip the fill below if
142 // the value being inserted is all zeros.
143 //
144 // Note that this is applicable for funcref tables when
145 // `tunables.table_lazy_init` is enabled as well. In that situation the
146 // null image means "go check the instance" and the instance created by
147 // `generate_table_export` says everything is null.
148 //
149 // In all cases a zero-initialized table will reflect all-null elements
150 // at runtime.
151 if init.is_zero_pattern() {
152 if cfg!(debug_assertions) {
153 let (table, _) = table.wasmtime_table(store, None);
154 table.debug_assert_all_zero();
155 }
156 return Ok(table);
157 }
158 table._fill(store, 0, init, ty.minimum())?;
159 Ok(table)
160 }
161
162 /// Returns the underlying type of this table, including its element type as
163 /// well as the maximum/minimum lower bounds.
164 ///
165 /// # Panics
166 ///
167 /// Panics if `store` does not own this table.
168 pub fn ty(&self, store: impl AsContext) -> TableType {
169 self.ty_(store.as_context().0)
170 }
171
172 pub(crate) fn ty_(&self, store: &StoreOpaque) -> TableType {
173 TableType::from_wasmtime_table(store.engine(), self.wasmtime_ty(store))
174 }
175
176 /// Returns the `vm::Table` within `store` as well as the optional
177 /// `GcStore` in use within `store`.
178 ///
179 /// # Panics
180 ///
181 /// Panics if this table does not belong to `store`.
182 fn wasmtime_table<'a>(
183 &self,
184 store: &'a mut StoreOpaque,
185 lazy_init_range: impl IntoIterator<Item = u64>,
186 ) -> (&'a mut vm::Table, Option<&'a mut GcStore>) {
187 self.instance.assert_belongs_to(store.id());
188 let (store, registry, instance) =
189 store.optional_gc_store_and_registry_and_instance_mut(self.instance.instance());
190
191 (
192 instance.get_defined_table_with_lazy_init(registry, self.index, lazy_init_range),
193 store,
194 )
195 }
196
197 /// Returns the table element value at `index`.
198 ///
199 /// Returns `None` if `index` is out of bounds.
200 ///
201 /// A GC reference is returned as an unrooted reference
202 /// ([`MaybeRooted::Unrooted`](crate::MaybeRooted::Unrooted)), valid until
203 /// the store's GC heap next changes; root it with [`Ref::ensure_rooted`]
204 /// to keep it for longer.
205 ///
206 /// # Panics
207 ///
208 /// Panics if `store` does not own this table.
209 pub fn get(&self, mut store: impl AsContextMut, index: u64) -> Option<Ref> {
210 let store = store.as_context_mut().0;
211 let (table, _gc_store) = self.wasmtime_table(store, [index]);
212 match table.element_type() {
213 TableElementType::Func => {
214 let ptr = table.get_func(index).ok()?;
215 Some(
216 // SAFETY: `store` owns this table, so therefore it owns all
217 // functions within the table too.
218 ptr.map(|p| unsafe { Func::from_vm_func_ref(store.id(), p) })
219 .into(),
220 )
221 }
222 TableElementType::GcRef => {
223 // Note that `unchecked_copy` is ok, since we only use the copy
224 // to create an unrooted reference just below, and nothing
225 // happens to the store in between.
226 let gc_ref = table.get_gc_ref(index).ok()?.map(|r| r.unchecked_copy());
227 Some(match self.ty_(store).element().heap_type().top() {
228 HeapTopType::Extern => {
229 Ref::from(gc_ref.map(|r| Unrooted::<ExternRef>::new(store, &r)))
230 }
231 HeapTopType::Any => {
232 Ref::from(gc_ref.map(|r| Unrooted::<AnyRef>::new(store, &r)))
233 }
234 HeapTopType::Exn => {
235 Ref::from(gc_ref.map(|r| Unrooted::<ExnRef>::new(store, &r)))
236 }
237 HeapTopType::Func | HeapTopType::Cont => unreachable!("not GC refs"),
238 })
239 }
240 // TODO(#10248) Required to support stack switching in the embedder
241 // API.
242 TableElementType::Cont => panic!("unimplemented table for cont"),
243 }
244 }
245
246 /// Writes the `val` provided into `index` within this table.
247 ///
248 /// # Errors
249 ///
250 /// Returns an error if `index` is out of bounds, if `val` does not have
251 /// the right type to be stored in this table, or if `val` belongs to a
252 /// different store.
253 ///
254 /// This function will return an [`OutOfMemory`][crate::OutOfMemory] error when
255 /// memory allocation fails. See the `OutOfMemory` type's documentation for
256 /// details on Wasmtime's out-of-memory handling.
257 ///
258 /// # Panics
259 ///
260 /// Panics if `store` does not own this table.
261 pub fn set(&self, mut store: impl AsContextMut, index: u64, val: Ref) -> Result<()> {
262 self.set_(store.as_context_mut().0, index, val)
263 }
264
265 pub(crate) fn set_(&self, store: &mut StoreOpaque, index: u64, val: Ref) -> Result<()> {
266 val.validate_rooted()?;
267 let ty = self.ty_(store);
268 match element_type(&ty) {
269 TableElementType::Func => {
270 let element = val.into_table_func(store, ty.element())?;
271 let (table, _gc_store) = self.wasmtime_table(store, iter::empty());
272 table.set_func(index, element)?;
273 }
274 TableElementType::GcRef => {
275 let mut store = AutoAssertNoGc::new(store);
276 let element = val.into_table_gc_ref(&mut store, ty.element())?;
277 // Note that `unchecked_copy` should be ok as we're under an
278 // `AutoAssertNoGc` which means that despite this not being
279 // rooted we don't have to worry about it going away.
280 let element = element.map(|r| r.unchecked_copy());
281 let (table, gc_store) = self.wasmtime_table(&mut store, iter::empty());
282 table.set_gc_ref(gc_store, index, element.as_ref())?;
283 }
284 // TODO(#10248) Required to support stack switching in the embedder
285 // API.
286 TableElementType::Cont => bail!("unimplemented table for cont"),
287 }
288 Ok(())
289 }
290
291 /// Returns the current size of this table.
292 ///
293 /// # Panics
294 ///
295 /// Panics if `store` does not own this table.
296 pub fn size(&self, store: impl AsContext) -> u64 {
297 self.size_(store.as_context().0)
298 }
299
300 pub(crate) fn size_(&self, store: &StoreOpaque) -> u64 {
301 // unwrap here should be ok because the runtime should always guarantee
302 // that we can fit the number of elements in a 64-bit integer.
303 u64::try_from(store[self.instance].table(self.index).current_elements).unwrap()
304 }
305
306 /// Grows the size of this table by `delta` more elements, initialization
307 /// all new elements to `init`.
308 ///
309 /// Returns the previous size of this table if successful.
310 ///
311 /// # Errors
312 ///
313 /// Returns an error if the table cannot be grown by `delta`, for example
314 /// if it would cause the table to exceed its maximum size. Also returns an
315 /// error if `init` is not of the right type or if `init` does not belong to
316 /// `store`.
317 ///
318 /// This function also returns an error when used with a
319 /// [`Store`](`crate::Store`) which has a
320 /// [`ResourceLimiterAsync`](`crate::ResourceLimiterAsync`) (see also:
321 /// [`Store::limiter_async`](`crate::Store::limiter_async`)). When using an
322 /// async resource limiter, use [`Table::grow_async`] instead.
323 ///
324 /// This function will handle out-of-memory conditions and report an error
325 /// in such cases, see the `OutOfMemory` type's documentation for details on
326 /// Wasmtime's out-of-memory handling. Note that the `OutOfMemory` type may
327 /// not literally be returned for detecting this condition.
328 ///
329 /// # Panics
330 ///
331 /// Panics if `store` does not own this table.
332 pub fn grow(&self, mut store: impl AsContextMut, delta: u64, init: Ref) -> Result<u64> {
333 let store = store.as_context_mut();
334 store.0.validate_sync_resource_limiter_and_store_opaque()?;
335 vm::assert_ready(self._grow(store, delta, init))
336 }
337
338 async fn _grow<T>(&self, store: StoreContextMut<'_, T>, delta: u64, init: Ref) -> Result<u64> {
339 let store = store.0;
340 let (mut limiter, store) = store.resource_limiter_and_store_opaque();
341 let limiter = limiter.as_mut();
342
343 // First, type-check to make sure that `init` does indeed match this
344 // table's element type.
345 let ty = self.ty_(store);
346 init.validate_rooted()?;
347 init.ensure_matches_ty(store, ty.element())
348 .context("type mismatch: value does not match table element type")?;
349
350 // SAFETY: the requirement here is that the new table elements, on
351 // success, are filled in with an appropriately typed value. That's done
352 // below in `_fill`.
353 let result = unsafe {
354 self.instance
355 .get_mut(store)
356 .defined_table_grow(self.index, limiter, delta)
357 .await?
358 };
359 let start = match result {
360 // unwrap here should be ok because the runtime should always
361 // guarantee that we can fit the table size in a 64-bit integer.
362 Some(size) => u64::try_from(size).unwrap(),
363 None => bail!("failed to grow table by `{delta}`"),
364 };
365 // This should be in-bounds and well-typed, meaning that it should not
366 // fail, hence the unwrap. Note that this is required for the safety of
367 // this operation because this table's type may be non-nullable elements
368 // which means this must happen after growth.
369 self._fill(store, start, init, delta).unwrap();
370 Ok(start)
371 }
372
373 /// Async variant of [`Table::grow`].
374 ///
375 /// Required when using a
376 /// [`ResourceLimiterAsync`](`crate::ResourceLimiterAsync`).
377 ///
378 /// # Errors
379 ///
380 /// This function may return errors for the same reasons as [`Table::grow`].
381 ///
382 /// # Panics
383 ///
384 /// This function will panic when if the store doesn't own the table.
385 #[cfg(feature = "async")]
386 pub async fn grow_async(
387 &self,
388 mut store: impl AsContextMut,
389 delta: u64,
390 init: Ref,
391 ) -> Result<u64> {
392 self._grow(store.as_context_mut(), delta, init).await
393 }
394
395 /// Copy `len` elements from `src_table[src_index..]` into
396 /// `dst_table[dst_index..]`.
397 ///
398 /// # Errors
399 ///
400 /// Returns an error if the range is out of bounds of either the source or
401 /// destination tables, or if the source table's element type does not match
402 /// the destination table's element type.
403 ///
404 /// This function will return an [`OutOfMemory`][crate::OutOfMemory] error when
405 /// memory allocation fails. See the `OutOfMemory` type's documentation for
406 /// details on Wasmtime's out-of-memory handling.
407 ///
408 /// # Panics
409 ///
410 /// Panics if `store` does not own either `dst_table` or `src_table`.
411 pub fn copy(
412 mut store: impl AsContextMut,
413 dst_table: &Table,
414 dst_index: u64,
415 src_table: &Table,
416 src_index: u64,
417 len: u64,
418 ) -> Result<()> {
419 let store = store.as_context_mut().0;
420
421 let src_range = src_index..src_index.checked_add(len).ok_or(Trap::TableOutOfBounds)?;
422 let dst_range = dst_index..dst_index.checked_add(len).ok_or(Trap::TableOutOfBounds)?;
423
424 // Bounds-check up front before any modifications to ensure everything
425 // is in-bounds.
426 if src_range.end > src_table.size_(store) || dst_range.end > dst_table.size_(store) {
427 return Err(Trap::TableOutOfBounds.into());
428 }
429
430 let dst_ty = dst_table.ty(&store);
431 let src_ty = src_table.ty(&store);
432 src_ty
433 .element()
434 .ensure_matches(store.engine(), dst_ty.element())
435 .context(
436 "type mismatch: source table's element type does not match \
437 destination table's element type",
438 )?;
439
440 let mut copy_elem = |src: u64, dst: u64| -> Result<()> {
441 let scope = store.enter_gc_lifo_scope();
442 let result = match src_table.get(&mut *store, src) {
443 // `get` returns an unrooted reference, which must be rooted
444 // (within the scope above) before `set` can store it.
445 Some(mut val) => val
446 .ensure_rooted(&mut *store)
447 .and_then(|()| dst_table.set(&mut *store, dst, val)),
448 None => Err(Trap::TableOutOfBounds.into()),
449 };
450 store.exit_gc_lifo_scope(scope);
451 result
452 };
453
454 // Do a forwards or backwards copy depending on the indices involved to
455 // ensure that elements that are part of the copy aren't accidentally
456 // clobbered.
457 if dst_index < src_index {
458 for (src, dst) in src_range.zip(dst_range) {
459 copy_elem(src, dst)?;
460 }
461 } else {
462 for (src, dst) in src_range.rev().zip(dst_range.rev()) {
463 copy_elem(src, dst)?;
464 }
465 }
466 Ok(())
467 }
468
469 /// Fill `table[dst..(dst + len)]` with the given value.
470 ///
471 /// # Errors
472 ///
473 /// Returns an error if
474 ///
475 /// * `val` is not of the same type as this table's
476 /// element type,
477 ///
478 /// * the region to be filled is out of bounds, or
479 ///
480 /// * `val` comes from a different `Store` from this table.
481 ///
482 /// This function will return an [`OutOfMemory`][crate::OutOfMemory] error when
483 /// memory allocation fails. See the `OutOfMemory` type's documentation for
484 /// details on Wasmtime's out-of-memory handling.
485 ///
486 /// # Panics
487 ///
488 /// Panics if `store` does not own either `dst_table` or `src_table`.
489 pub fn fill(&self, mut store: impl AsContextMut, dst: u64, val: Ref, len: u64) -> Result<()> {
490 self._fill(store.as_context_mut().0, dst, val, len)
491 }
492
493 pub(crate) fn _fill(
494 &self,
495 store: &mut StoreOpaque,
496 dst: u64,
497 val: Ref,
498 len: u64,
499 ) -> Result<()> {
500 let ty = self.ty_(store);
501 val.validate_rooted()?;
502 val.ensure_matches_ty(store, ty.element())
503 .context("type mismatch: value does not match table element type")?;
504 let end = dst.checked_add(len).ok_or(Trap::TableOutOfBounds)?;
505 if end > self.size_(store) {
506 bail!(Trap::TableOutOfBounds);
507 }
508 for i in dst..dst + len {
509 self.set_(&mut *store, i, val.clone())?;
510 }
511 Ok(())
512 }
513
514 #[cfg(feature = "gc")]
515 pub(crate) fn trace_roots(&self, store: &mut StoreOpaque, gc_roots_list: &mut vm::GcRootsList) {
516 if !self
517 .ty_(store)
518 .element()
519 .is_vmgcref_type_and_points_to_object()
520 {
521 return;
522 }
523
524 let (table, _) = self.wasmtime_table(store, iter::empty());
525 for gc_ref in table.gc_refs_mut() {
526 if let Some(gc_ref) = gc_ref {
527 unsafe {
528 gc_roots_list.add_vmgcref_root(gc_ref.into(), "Wasm table element");
529 }
530 }
531 }
532 }
533
534 pub(crate) fn from_raw(instance: StoreInstanceId, index: DefinedTableIndex) -> Table {
535 Table { instance, index }
536 }
537
538 pub(crate) fn wasmtime_ty<'a>(&self, store: &'a StoreOpaque) -> &'a wasmtime_environ::Table {
539 let module = store[self.instance].env_module();
540 let index = module.table_index(self.index);
541 &module.tables[index]
542 }
543
544 pub(crate) fn vmimport(&self, store: &StoreOpaque) -> vm::VMTableImport {
545 let instance = &store[self.instance];
546 vm::VMTableImport {
547 from: instance.table_ptr(self.index).into(),
548 vmctx: instance.vmctx().into(),
549 index: self.index,
550 }
551 }
552
553 pub(crate) fn comes_from_same_store(&self, store: &StoreOpaque) -> bool {
554 store.id() == self.instance.store_id()
555 }
556
557 /// Returns a stable identifier for this table within its store.
558 ///
559 /// This allows distinguishing tables when introspecting them
560 /// e.g. via debug APIs.
561 #[cfg(feature = "debug")]
562 pub fn debug_index_in_store(&self) -> u64 {
563 u64::from(self.instance.instance().as_u32()) << 32 | u64::from(self.index.as_u32())
564 }
565
566 /// Get a stable hash key for this table.
567 ///
568 /// Even if the same underlying table definition is added to the
569 /// `StoreData` multiple times and becomes multiple `wasmtime::Table`s,
570 /// this hash key will be consistent across all of these tables.
571 #[cfg_attr(
572 not(test),
573 expect(dead_code, reason = "Not used yet, but added for consistency")
574 )]
575 pub(crate) fn hash_key(&self, store: &StoreOpaque) -> impl core::hash::Hash + Eq + use<'_> {
576 store[self.instance].table_ptr(self.index).as_ptr().addr()
577 }
578}
579
580fn element_type(ty: &TableType) -> TableElementType {
581 match ty.element().heap_type().top() {
582 HeapTopType::Func => TableElementType::Func,
583 HeapTopType::Exn | HeapTopType::Extern | HeapTopType::Any => TableElementType::GcRef,
584 HeapTopType::Cont => TableElementType::Cont,
585 }
586}
587
588impl Ref {
589 fn into_table_func(
590 self,
591 store: &mut StoreOpaque,
592 ty: &RefType,
593 ) -> Result<Option<NonNull<VMFuncRef>>> {
594 self.ensure_matches_ty(store, &ty)
595 .context("type mismatch: value does not match table element type")?;
596
597 match (self, ty.heap_type().top()) {
598 (Ref::Func(None), HeapTopType::Func) => {
599 assert!(ty.is_nullable());
600 Ok(None)
601 }
602 (Ref::Func(Some(f)), HeapTopType::Func) => {
603 debug_assert!(
604 f.comes_from_same_store(store),
605 "checked in `ensure_matches_ty`"
606 );
607 Ok(Some(f.vm_func_ref(store)))
608 }
609
610 _ => unreachable!("checked that the value matches the type above"),
611 }
612 }
613
614 fn into_table_gc_ref<'a>(
615 &'a self,
616 store: &'a mut AutoAssertNoGc<'_>,
617 ty: &RefType,
618 ) -> Result<Option<&'a VMGcRef>> {
619 self.ensure_matches_ty(store, &ty)
620 .context("type mismatch: value does not match table element type")?;
621
622 match (self, ty.heap_type().top()) {
623 (Ref::Extern(e), HeapTopType::Extern) => match e {
624 None => {
625 assert!(ty.is_nullable());
626 Ok(None)
627 }
628 Some(e) => Ok(Some(e.try_gc_ref(store)?)),
629 },
630
631 (Ref::Any(a), HeapTopType::Any) => match a {
632 None => {
633 assert!(ty.is_nullable());
634 Ok(None)
635 }
636 Some(a) => Ok(Some(a.try_gc_ref(store)?)),
637 },
638
639 (Ref::Exn(e), HeapTopType::Exn) => match e {
640 None => {
641 assert!(ty.is_nullable());
642 Ok(None)
643 }
644 Some(e) => Ok(Some(e.try_gc_ref(store)?)),
645 },
646
647 _ => unreachable!("checked that the value matches the type above"),
648 }
649 }
650
651 fn is_zero_pattern(&self) -> bool {
652 match self {
653 Ref::Extern(None) | Ref::Any(None) | Ref::Exn(None) | Ref::Func(None) => true,
654 Ref::Extern(Some(_)) | Ref::Any(Some(_)) | Ref::Exn(Some(_)) | Ref::Func(Some(_)) => {
655 false
656 }
657 }
658 }
659}
660
661#[cfg(test)]
662mod tests {
663 use super::*;
664 use crate::{Instance, Module, Store};
665
666 #[test]
667 fn hash_key_is_stable_across_duplicate_store_data_entries() -> Result<()> {
668 let mut store = Store::<()>::default();
669 let module = Module::new(
670 store.engine(),
671 r#"
672 (module
673 (table (export "t") 1 1 externref)
674 )
675 "#,
676 )?;
677 let instance = Instance::new(&mut store, &module, &[])?;
678
679 // Each time we `get_table`, we call `Table::from_wasmtime` which adds
680 // a new entry to `StoreData`, so `t1` and `t2` will have different
681 // indices into `StoreData`.
682 let t1 = instance.get_table(&mut store, "t").unwrap();
683 let t2 = instance.get_table(&mut store, "t").unwrap();
684
685 // That said, they really point to the same table.
686 assert!(t1.get(&mut store, 0).unwrap().unwrap_extern().is_none());
687 assert!(t2.get(&mut store, 0).unwrap().unwrap_extern().is_none());
688 let e = ExternRef::new(&mut store, 42)?;
689 t1.set(&mut store, 0, e.into())?;
690 assert!(t1.get(&mut store, 0).unwrap().unwrap_extern().is_some());
691 assert!(t2.get(&mut store, 0).unwrap().unwrap_extern().is_some());
692
693 // And therefore their hash keys are the same.
694 assert!(t1.hash_key(&store.as_context().0) == t2.hash_key(&store.as_context().0));
695
696 // But the hash keys are different from different tables.
697 let instance2 = Instance::new(&mut store, &module, &[])?;
698 let t3 = instance2.get_table(&mut store, "t").unwrap();
699 assert!(t1.hash_key(&store.as_context().0) != t3.hash_key(&store.as_context().0));
700
701 Ok(())
702 }
703
704 #[test]
705 fn grow_is_send() {
706 fn _assert_send<T: Send>(_: T) {}
707 fn _grow(table: &Table, store: &mut Store<()>, init: Ref) {
708 _assert_send(table.grow(store, 0, init))
709 }
710 }
711
712 #[test]
713 #[cfg(feature = "gc")]
714 fn grow_with_unrooted_ref_returns_err() -> Result<()> {
715 let mut config = crate::Config::new();
716 config.wasm_gc(true);
717 let engine = crate::Engine::new(&config)?;
718 let mut store = Store::new(&engine, ());
719 let ty = crate::TableType::new(crate::RefType::EXTERNREF, 2, None)?;
720 let table = Table::new(&mut store, ty, Ref::Extern(None))?;
721
722 let unrooted = {
723 let mut scope = crate::RootScope::new(&mut store);
724 ExternRef::new(&mut scope, 1u32)?
725 };
726
727 let res = table.grow(&mut store, 1, Ref::from(unrooted));
728 assert!(res.is_err());
729 assert_eq!(table.size(&store), 2);
730 Ok(())
731 }
732}