Skip to main content

wasmtime/runtime/externals/
global.rs

1use crate::prelude::*;
2use crate::runtime::vm::{self, VMGlobalDefinition, VMGlobalKind, VMOpaqueContext};
3use crate::{
4    AnyRef, AsContext, AsContextMut, ExnRef, ExternRef, Func, GlobalType, HeapType, Mutability,
5    Ref, Unrooted, Val, ValType,
6    store::{AutoAssertNoGc, InstanceId, StoreId, StoreInstanceId, StoreOpaque},
7    trampoline::generate_global_export,
8};
9use core::ptr::NonNull;
10use wasmtime_environ::DefinedGlobalIndex;
11
12/// A WebAssembly `global` value which can be read and written to.
13///
14/// A `global` in WebAssembly is sort of like a global variable within an
15/// [`Instance`](crate::Instance). The `global.get` and `global.set`
16/// instructions will modify and read global values in a wasm module. Globals
17/// can either be imported or exported from wasm modules.
18///
19/// A [`Global`] "belongs" to the store that it was originally created within
20/// (either via [`Global::new`] or via instantiating a
21/// [`Module`](crate::Module)). Operations on a [`Global`] only work with the
22/// store it belongs to, and if another store is passed in by accident then
23/// methods will panic.
24#[derive(Copy, Clone, Debug)]
25#[repr(C)] // here for the C API
26pub struct Global {
27    /// The store that this global belongs to.
28    store: StoreId,
29    /// Either `InstanceId` or `ComponentInstanceId` internals depending on
30    /// `kind` below.
31    instance: u32,
32    /// Which method of definition was used when creating this global.
33    kind: VMGlobalKind,
34}
35
36// Double-check that the C representation in `extern.h` matches our in-Rust
37// representation here in terms of size/alignment/etc.
38const _: () = {
39    #[repr(C)]
40    struct C(u64, u32, u32, u32);
41    assert!(core::mem::size_of::<C>() == core::mem::size_of::<Global>());
42    assert!(core::mem::align_of::<C>() == core::mem::align_of::<Global>());
43    assert!(core::mem::offset_of!(Global, store) == 0);
44};
45
46impl Global {
47    /// Creates a new WebAssembly `global` value with the provide type `ty` and
48    /// initial value `val`.
49    ///
50    /// The `store` argument will be the owner of the [`Global`] returned. Using
51    /// the returned [`Global`] other items in the store may access this global.
52    /// For example this could be provided as an argument to
53    /// [`Instance::new`](crate::Instance::new) or
54    /// [`Linker::define`](crate::Linker::define).
55    ///
56    /// # Errors
57    ///
58    /// Returns an error if the `ty` provided does not match the type of the
59    /// value `val`, or if `val` comes from a different store than `store`.
60    ///
61    /// Returns an error if the content type of `ty` was not created with the
62    /// same [`Engine`](crate::Engine) as `store`.
63    ///
64    /// This function will return an [`OutOfMemory`][crate::OutOfMemory] error when
65    /// memory allocation fails. See the `OutOfMemory` type's documentation for
66    /// details on Wasmtime's out-of-memory handling.
67    ///
68    /// # Examples
69    ///
70    /// ```
71    /// # use wasmtime::*;
72    /// # fn main() -> Result<()> {
73    /// let engine = Engine::default();
74    /// let mut store = Store::new(&engine, ());
75    ///
76    /// let ty = GlobalType::new(ValType::I32, Mutability::Const);
77    /// let i32_const = Global::new(&mut store, ty, 1i32.into())?;
78    /// let ty = GlobalType::new(ValType::F64, Mutability::Var);
79    /// let f64_mut = Global::new(&mut store, ty, 2.0f64.into())?;
80    ///
81    /// let module = Module::new(
82    ///     &engine,
83    ///     "(module
84    ///         (global (import \"\" \"i32-const\") i32)
85    ///         (global (import \"\" \"f64-mut\") (mut f64))
86    ///     )"
87    /// )?;
88    ///
89    /// let mut linker = Linker::new(&engine);
90    /// linker.define(&store, "", "i32-const", i32_const)?;
91    /// linker.define(&store, "", "f64-mut", f64_mut)?;
92    ///
93    /// let instance = linker.instantiate(&mut store, &module)?;
94    /// // ...
95    /// # Ok(())
96    /// # }
97    /// ```
98    pub fn new(mut store: impl AsContextMut, ty: GlobalType, val: Val) -> Result<Global> {
99        Global::_new(store.as_context_mut().0, ty, val)
100    }
101
102    fn _new(store: &mut StoreOpaque, ty: GlobalType, val: Val) -> Result<Global> {
103        val.validate_rooted()?;
104        val.ensure_matches_ty(store, ty.content()).context(
105            "type mismatch: initial value provided does not match the type of this global",
106        )?;
107        generate_global_export(store, ty, val)
108    }
109
110    pub(crate) fn new_host(store: &StoreOpaque, index: DefinedGlobalIndex) -> Global {
111        Global {
112            store: store.id(),
113            instance: 0,
114            kind: VMGlobalKind::Host(index),
115        }
116    }
117
118    pub(crate) fn new_instance(
119        store: &StoreOpaque,
120        instance: InstanceId,
121        index: DefinedGlobalIndex,
122    ) -> Global {
123        Global {
124            store: store.id(),
125            instance: instance.as_u32(),
126            kind: VMGlobalKind::Instance(index),
127        }
128    }
129
130    /// Returns the underlying type of this `global`.
131    ///
132    /// # Panics
133    ///
134    /// Panics if `store` does not own this global.
135    pub fn ty(&self, store: impl AsContext) -> GlobalType {
136        self._ty(store.as_context().0)
137    }
138
139    pub(crate) fn _ty(&self, store: &StoreOpaque) -> GlobalType {
140        GlobalType::from_wasmtime_global(store.engine(), self.wasmtime_ty(store))
141    }
142
143    /// Returns the current [`Val`] of this global.
144    ///
145    /// A GC reference is returned as an unrooted reference
146    /// ([`MaybeRooted::Unrooted`](crate::MaybeRooted::Unrooted)), valid until
147    /// the store's GC heap next changes; root it with
148    /// [`Val::ensure_rooted`] to keep it for longer.
149    ///
150    /// # Panics
151    ///
152    /// Panics if `store` does not own this global.
153    pub fn get(&self, store: impl AsContext) -> Val {
154        self._get(store.as_context().0)
155    }
156
157    /// Returns the current [`Val`] of this global if it has a numeric type
158    /// (`i32`, `i64`, `f32`, `f64`, or `v128`), or `None` if it holds a
159    /// reference.
160    ///
161    /// Like [`Global::get`], this only needs shared access to the store, so it
162    /// is usable where only an [`AsContext`] is available, for example from
163    /// epoch or call hooks.
164    ///
165    /// # Panics
166    ///
167    /// Panics if `store` does not own this global.
168    pub fn get_numeric(&self, store: impl AsContext) -> Option<Val> {
169        self._get_numeric(store.as_context().0)
170    }
171
172    fn _get_numeric(&self, store: &StoreOpaque) -> Option<Val> {
173        unsafe {
174            let definition = self.definition(store).as_ref();
175            match self._ty(store).content() {
176                ValType::I32 => Some(Val::from(definition.get_i32())),
177                ValType::I64 => Some(Val::from(definition.get_i64())),
178                ValType::F32 => Some(Val::F32(definition.get_f32_bits())),
179                ValType::F64 => Some(Val::F64(definition.get_f64_bits())),
180                ValType::V128 => Some(Val::V128(definition.get_u128().into())),
181                ValType::Ref(_) => None,
182            }
183        }
184    }
185
186    pub(crate) fn _get(&self, store: &StoreOpaque) -> Val {
187        unsafe {
188            let definition = self.definition(store).as_ref();
189            match self._ty(store).content() {
190                ValType::I32 | ValType::I64 | ValType::F32 | ValType::F64 | ValType::V128 => self
191                    ._get_numeric(store)
192                    .expect("numeric globals always have a numeric value"),
193                ValType::Ref(ref_ty) => {
194                    let reference: Ref = match ref_ty.heap_type() {
195                        HeapType::Func | HeapType::ConcreteFunc(_) => Ref::Func(
196                            definition
197                                .get_func_ref()
198                                .map(|f| Func::from_vm_func_ref(store.id(), f)),
199                        ),
200
201                        HeapType::NoFunc => Ref::Func(None),
202
203                        HeapType::Extern => definition
204                            .as_gc_ref()
205                            .map(|r| Unrooted::<ExternRef>::new(store, r))
206                            .into(),
207
208                        HeapType::NoCont | HeapType::ConcreteCont(_) | HeapType::Cont => {
209                            // TODO(#10248) Required to support stack switching in the embedder API.
210                            unimplemented!()
211                        }
212
213                        HeapType::NoExtern => Ref::Extern(None),
214
215                        HeapType::Exn => definition
216                            .as_gc_ref()
217                            .map(|r| Unrooted::<ExnRef>::new(store, r))
218                            .into(),
219
220                        HeapType::Any
221                        | HeapType::Eq
222                        | HeapType::I31
223                        | HeapType::Struct
224                        | HeapType::ConcreteStruct(_)
225                        | HeapType::Array
226                        | HeapType::ConcreteArray(_) => definition
227                            .as_gc_ref()
228                            .map(|r| Unrooted::<AnyRef>::new(store, r))
229                            .into(),
230
231                        HeapType::NoExn => Ref::Exn(None),
232
233                        HeapType::None => Ref::Any(None),
234                    };
235                    debug_assert!(
236                        ref_ty.is_nullable() || !reference.is_null(),
237                        "if the type is non-nullable, we better have a non-null reference"
238                    );
239                    reference.into()
240                }
241            }
242        }
243    }
244
245    /// Attempts to set the current value of this global to [`Val`].
246    ///
247    /// # Errors
248    ///
249    /// Returns an error if this global has a different type than `Val`, if
250    /// it's not a mutable global, or if `val` comes from a different store than
251    /// the one provided.
252    ///
253    /// This function will return an [`OutOfMemory`][crate::OutOfMemory] error when
254    /// memory allocation fails. See the `OutOfMemory` type's documentation for
255    /// details on Wasmtime's out-of-memory handling.
256    ///
257    /// # Panics
258    ///
259    /// Panics if `store` does not own this global.
260    pub fn set(&self, mut store: impl AsContextMut, val: Val) -> Result<()> {
261        self._set(store.as_context_mut().0, val)
262    }
263
264    pub(crate) fn _set(&self, store: &mut StoreOpaque, val: Val) -> Result<()> {
265        let global_ty = self._ty(&store);
266        if global_ty.mutability() != Mutability::Var {
267            bail!("immutable global cannot be set");
268        }
269        val.validate_rooted()?;
270        val.ensure_matches_ty(&store, global_ty.content())
271            .context("type mismatch: attempt to set global to value of wrong type")?;
272
273        // SAFETY: mutability and a type-check above makes this safe to perform.
274        unsafe { self.set_unchecked(store, &val) }
275    }
276
277    /// Sets this global to `val`.
278    ///
279    /// # Safety
280    ///
281    /// This function requires that `val` is of the correct type for this
282    /// global. Furthermore this requires that the global is mutable or this is
283    /// the first time the global is initialized.
284    pub(crate) unsafe fn set_unchecked(&self, store: &mut StoreOpaque, val: &Val) -> Result<()> {
285        let mut store = AutoAssertNoGc::new(store);
286        unsafe {
287            let definition = self.definition(&store).as_mut();
288            match val {
289                Val::I32(i) => definition.set_i32(*i),
290                Val::I64(i) => definition.set_i64(*i),
291                Val::F32(f) => definition.set_f32_bits(*f),
292                Val::F64(f) => definition.set_f64_bits(*f),
293                Val::V128(i) => definition.set_u128((*i).into()),
294                Val::FuncRef(f) => {
295                    definition.set_func_ref(f.map(|f| f.vm_func_ref(&store)));
296                }
297                Val::ExternRef(e) => {
298                    let new = match e {
299                        None => None,
300                        Some(e) => Some(e.try_gc_ref(&store)?.unchecked_copy()),
301                    };
302                    let new = new.as_ref();
303                    definition.write_gc_ref(&mut store, new)?;
304                }
305                Val::AnyRef(a) => {
306                    let new = match a {
307                        None => None,
308                        Some(a) => Some(a.try_gc_ref(&store)?.unchecked_copy()),
309                    };
310                    let new = new.as_ref();
311                    definition.write_gc_ref(&mut store, new)?;
312                }
313                Val::ExnRef(e) => {
314                    let new = match e {
315                        None => None,
316                        Some(e) => Some(e.try_gc_ref(&store)?.unchecked_copy()),
317                    };
318                    let new = new.as_ref();
319                    definition.write_gc_ref(&mut store, new)?;
320                }
321                Val::ContRef(None) => {
322                    // Allow null continuation references for globals - these are just placeholders
323                    definition.write_gc_ref(&mut store, None)?;
324                }
325                Val::ContRef(Some(_)) => {
326                    // TODO(#10248): Implement non-null global continuation reference handling
327                    return Err(crate::format_err!(
328                        "setting non-null continuation references in globals not yet supported"
329                    ));
330                }
331            }
332        }
333        Ok(())
334    }
335
336    #[cfg(feature = "gc")]
337    pub(crate) fn trace_root(&self, store: &mut StoreOpaque, gc_roots_list: &mut vm::GcRootsList) {
338        if let Some(ref_ty) = self._ty(store).content().as_ref() {
339            if !ref_ty.is_vmgcref_type_and_points_to_object() {
340                return;
341            }
342
343            if let Some(gc_ref) = unsafe { self.definition(store).as_mut().as_gc_ref_mut() } {
344                unsafe {
345                    gc_roots_list.add_vmgcref_root(gc_ref.into(), "Wasm global");
346                }
347            }
348        }
349    }
350
351    pub(crate) fn from_host(store: StoreId, index: DefinedGlobalIndex) -> Global {
352        Global {
353            store,
354            instance: 0,
355            kind: VMGlobalKind::Host(index),
356        }
357    }
358
359    pub(crate) fn from_core(instance: StoreInstanceId, index: DefinedGlobalIndex) -> Global {
360        Global {
361            store: instance.store_id(),
362            instance: instance.instance().as_u32(),
363            kind: VMGlobalKind::Instance(index),
364        }
365    }
366
367    #[cfg(feature = "component-model")]
368    pub(crate) fn from_component_flags(
369        instance: crate::component::store::StoreComponentInstanceId,
370        index: wasmtime_environ::component::RuntimeComponentInstanceIndex,
371    ) -> Global {
372        Global {
373            store: instance.store_id(),
374            instance: instance.instance().as_u32(),
375            kind: VMGlobalKind::ComponentFlags(index),
376        }
377    }
378
379    pub(crate) fn wasmtime_ty<'a>(&self, store: &'a StoreOpaque) -> &'a wasmtime_environ::Global {
380        self.store.assert_belongs_to(store.id());
381        match self.kind {
382            VMGlobalKind::Instance(index) => {
383                let instance = InstanceId::from_u32(self.instance);
384                let module = store.instance(instance).env_module();
385                let index = module.global_index(index);
386                &module.globals[index]
387            }
388            VMGlobalKind::Host(index) => unsafe { &store.host_globals()[index].get().as_ref().ty },
389            #[cfg(feature = "component-model")]
390            VMGlobalKind::ComponentFlags(_) => {
391                const TY: wasmtime_environ::Global = wasmtime_environ::Global {
392                    mutability: true,
393                    wasm_ty: wasmtime_environ::WasmValType::I32,
394                };
395                &TY
396            }
397        }
398    }
399
400    pub(crate) fn vmimport(&self, store: &StoreOpaque) -> vm::VMGlobalImport {
401        let vmctx = match self.kind {
402            VMGlobalKind::Instance(_) => {
403                let instance = InstanceId::from_u32(self.instance);
404                Some(VMOpaqueContext::from_vmcontext(store.instance(instance).vmctx()).into())
405            }
406            VMGlobalKind::Host(_) => None,
407            #[cfg(feature = "component-model")]
408            VMGlobalKind::ComponentFlags(_) => {
409                let instance = crate::component::ComponentInstanceId::from_u32(self.instance);
410                Some(
411                    VMOpaqueContext::from_vmcomponent(store.component_instance(instance).vmctx())
412                        .into(),
413                )
414            }
415        };
416        vm::VMGlobalImport {
417            from: self.definition(store).into(),
418            vmctx,
419            kind: self.kind,
420        }
421    }
422
423    pub(crate) fn comes_from_same_store(&self, store: &StoreOpaque) -> bool {
424        store.id() == self.store
425    }
426
427    /// Returns a stable identifier for this global within its store.
428    ///
429    /// This allows distinguishing globals when introspecting them
430    /// e.g. via debug APIs.
431    #[cfg(feature = "debug")]
432    pub fn debug_index_in_store(&self) -> u64 {
433        match self.kind {
434            VMGlobalKind::Instance(idx) => u64::from(self.instance) << 32 | u64::from(idx.as_u32()),
435            VMGlobalKind::Host(idx) => u64::from(u32::MAX) << 32 | u64::from(idx.as_u32()),
436            #[cfg(feature = "component-model")]
437            VMGlobalKind::ComponentFlags(idx) => {
438                u64::from(self.instance) << 32 | u64::from(idx.as_u32())
439            }
440        }
441    }
442
443    /// Get a stable hash key for this global.
444    ///
445    /// Even if the same underlying global definition is added to the
446    /// `StoreData` multiple times and becomes multiple `wasmtime::Global`s,
447    /// this hash key will be consistent across all of these globals.
448    #[cfg(feature = "coredump")]
449    pub(crate) fn hash_key(&self, store: &StoreOpaque) -> impl core::hash::Hash + Eq + use<> {
450        self.definition(store).as_ptr().addr()
451    }
452
453    fn definition(&self, store: &StoreOpaque) -> NonNull<VMGlobalDefinition> {
454        self.store.assert_belongs_to(store.id());
455        match self.kind {
456            VMGlobalKind::Instance(index) => {
457                let instance = InstanceId::from_u32(self.instance);
458                store.instance(instance).global_ptr(index)
459            }
460            VMGlobalKind::Host(index) => unsafe {
461                NonNull::from(&mut store.host_globals()[index].get().as_mut().global)
462            },
463            #[cfg(feature = "component-model")]
464            VMGlobalKind::ComponentFlags(index) => {
465                let instance = crate::component::ComponentInstanceId::from_u32(self.instance);
466                store
467                    .component_instance(instance)
468                    .instance_flags(index)
469                    .as_raw()
470            }
471        }
472    }
473}
474
475#[cfg(test)]
476mod tests {
477    use super::*;
478    use crate::{Instance, Module, Store};
479
480    #[test]
481    fn hash_key_is_stable_across_duplicate_store_data_entries() -> Result<()> {
482        let mut store = Store::<()>::default();
483        let module = Module::new(
484            store.engine(),
485            r#"
486                (module
487                    (global (export "g") (mut i32) (i32.const 0))
488                )
489            "#,
490        )?;
491        let instance = Instance::new(&mut store, &module, &[])?;
492
493        // Each time we `get_global`, we call `Global::from_wasmtime` which adds
494        // a new entry to `StoreData`, so `g1` and `g2` will have different
495        // indices into `StoreData`.
496        let g1 = instance.get_global(&mut store, "g").unwrap();
497        let g2 = instance.get_global(&mut store, "g").unwrap();
498
499        // That said, they really point to the same global.
500        assert_eq!(g1.get(&mut store).unwrap_i32(), 0);
501        assert_eq!(g2.get(&mut store).unwrap_i32(), 0);
502        g1.set(&mut store, Val::I32(42))?;
503        assert_eq!(g1.get(&mut store).unwrap_i32(), 42);
504        assert_eq!(g2.get(&mut store).unwrap_i32(), 42);
505
506        // And therefore their hash keys are the same.
507        assert!(g1.hash_key(&store.as_context().0) == g2.hash_key(&store.as_context().0));
508
509        // But the hash keys are different from different globals.
510        let instance2 = Instance::new(&mut store, &module, &[])?;
511        let g3 = instance2.get_global(&mut store, "g").unwrap();
512        assert!(g1.hash_key(&store.as_context().0) != g3.hash_key(&store.as_context().0));
513
514        Ok(())
515    }
516}