wasmer_vm/
global.rs

1use crate::{store::MaybeInstanceOwned, vmcontext::VMGlobalDefinition};
2use std::{cell::UnsafeCell, ptr::NonNull};
3use wasmer_types::GlobalType;
4
5/// A Global instance
6#[derive(Debug)]
7pub struct VMGlobal {
8    ty: GlobalType,
9    vm_global_definition: MaybeInstanceOwned<VMGlobalDefinition>,
10}
11
12impl VMGlobal {
13    /// Create a new, zero bit-pattern initialized global from a [`GlobalType`].
14    pub fn new(global_type: GlobalType) -> Self {
15        Self {
16            ty: global_type,
17            vm_global_definition: MaybeInstanceOwned::Host(Box::new(UnsafeCell::new(
18                VMGlobalDefinition::new(),
19            ))),
20        }
21    }
22
23    /// Create a new global backed by a `VMGlobalDefinition` stored inline in a `VMContext`.
24    ///
25    /// # Safety
26    /// - `vm_definition_location` must be a valid, properly aligned location for
27    ///   a `VMGlobalDefinition`.
28    pub unsafe fn new_instance(
29        global_type: GlobalType,
30        vm_definition_location: NonNull<VMGlobalDefinition>,
31    ) -> Self {
32        unsafe {
33            vm_definition_location
34                .as_ptr()
35                .write(VMGlobalDefinition::new());
36        }
37        Self {
38            ty: global_type,
39            vm_global_definition: MaybeInstanceOwned::Instance(vm_definition_location),
40        }
41    }
42
43    /// Get the type of the global.
44    pub fn ty(&self) -> &GlobalType {
45        &self.ty
46    }
47
48    /// Get a pointer to the underlying definition used by the generated code.
49    pub fn vmglobal(&self) -> NonNull<VMGlobalDefinition> {
50        self.vm_global_definition.as_ptr()
51    }
52
53    /// Copies this global
54    pub fn copy_on_write(&self) -> Self {
55        unsafe {
56            Self {
57                ty: self.ty,
58                vm_global_definition: MaybeInstanceOwned::Host(Box::new(UnsafeCell::new(
59                    self.vm_global_definition.as_ptr().as_ref().clone(),
60                ))),
61            }
62        }
63    }
64}