wasmer_vm/instance/
ref.rs

1use super::Instance;
2use std::alloc::Layout;
3use std::convert::TryFrom;
4use std::ptr::{self, NonNull};
5use std::sync::{Arc, Weak};
6
7/// Dynamic instance allocation.
8///
9/// This structure has a C representation because `Instance` is
10/// dynamically-sized, and the `instance` field must be last.
11///
12/// This `InstanceRef` must be freed with [`InstanceInner::deallocate_instance`]
13/// if and only if it has been set correctly. The `Drop` implementation of
14/// [`InstanceInner`] calls its `deallocate_instance` method without
15/// checking if this property holds, only when `Self.strong` is equal to 1.
16#[derive(Debug)]
17#[repr(C)]
18struct InstanceInner {
19    /// The layout of `Instance` (which can vary).
20    instance_layout: Layout,
21
22    /// The `Instance` itself. It must be the last field of
23    /// `InstanceRef` since `Instance` is dyamically-sized.
24    ///
25    /// `Instance` must not be dropped manually by Rust, because it's
26    /// allocated manually with `alloc` and a specific layout (Rust
27    /// would be able to drop `Instance` itself but it will imply a
28    /// memory leak because of `alloc`).
29    ///
30    /// No one in the code has a copy of the `Instance`'s
31    /// pointer. `Self` is the only one.
32    instance: NonNull<Instance>,
33}
34
35impl InstanceInner {
36    /// Deallocate `Instance`.
37    ///
38    /// # Safety
39    ///
40    /// `Self.instance` must be correctly set and filled before being
41    /// dropped and deallocated.
42    unsafe fn deallocate_instance(&mut self) {
43        let instance_ptr = self.instance.as_ptr();
44
45        ptr::drop_in_place(instance_ptr);
46        std::alloc::dealloc(instance_ptr as *mut u8, self.instance_layout);
47    }
48
49    /// Get a reference to the `Instance`.
50    #[inline]
51    pub(crate) fn as_ref(&self) -> &Instance {
52        // SAFETY: The pointer is properly aligned, it is
53        // “dereferencable”, it points to an initialized memory of
54        // `Instance`, and the reference has the lifetime `'a`.
55        unsafe { self.instance.as_ref() }
56    }
57
58    #[inline]
59    pub(super) fn as_mut(&mut self) -> &mut Instance {
60        unsafe { self.instance.as_mut() }
61    }
62}
63
64impl PartialEq for InstanceInner {
65    /// Two `InstanceInner` are equal if and only if
66    /// `Self.instance` points to the same location.
67    fn eq(&self, other: &Self) -> bool {
68        self.instance == other.instance
69    }
70}
71
72impl Drop for InstanceInner {
73    /// Drop the `InstanceInner`.
74    fn drop(&mut self) {
75        unsafe { Self::deallocate_instance(self) };
76    }
77}
78
79/// TODO: Review this super carefully.
80unsafe impl Send for InstanceInner {}
81unsafe impl Sync for InstanceInner {}
82
83/// An `InstanceRef` is responsible to properly deallocate,
84/// and to give access to an `Instance`, in such a way that `Instance`
85/// is unique, can be shared, safely, across threads, without
86/// duplicating the pointer in multiple locations. `InstanceRef`
87/// must be the only “owner” of an `Instance`.
88///
89/// Consequently, one must not share `Instance` but
90/// `InstanceRef`. It acts like an Atomically Reference Counter
91/// to `Instance`. In short, `InstanceRef` is roughly a
92/// simplified version of `std::sync::Arc`.
93///
94/// Note for the curious reader: [`InstanceAllocator::new`]
95/// and [`InstanceHandle::new`] will respectively allocate a proper
96/// `Instance` and will fill it correctly.
97///
98/// A little bit of background: The initial goal was to be able to
99/// share an [`Instance`] between an [`InstanceHandle`] and the module
100/// exports, so that one can drop a [`InstanceHandle`] but still being
101/// able to use the exports properly.
102#[derive(Debug, PartialEq, Clone)]
103pub struct InstanceRef(Arc<InstanceInner>);
104
105impl InstanceRef {
106    /// Create a new `InstanceRef`. It allocates nothing. It fills
107    /// nothing. The `Instance` must be already valid and
108    /// filled.
109    ///
110    /// # Safety
111    ///
112    /// `instance` must a non-null, non-dangling, properly aligned,
113    /// and correctly initialized pointer to `Instance`. See
114    /// [`InstanceAllocator`] for an example of how to correctly use
115    /// this API.
116    pub(super) unsafe fn new(instance: NonNull<Instance>, instance_layout: Layout) -> Self {
117        Self(Arc::new(InstanceInner {
118            instance_layout,
119            instance,
120        }))
121    }
122
123    /// Get a reference to the `Instance`.
124    #[inline]
125    pub(crate) fn as_ref(&self) -> &Instance {
126        (&*self.0).as_ref()
127    }
128
129    /// Only succeeds if ref count is 1.
130    #[inline]
131    pub(super) fn as_mut(&mut self) -> Option<&mut Instance> {
132        Some(Arc::get_mut(&mut self.0)?.as_mut())
133    }
134
135    /// Like [`InstanceRef::as_mut`] but always succeeds.
136    /// May cause undefined behavior if used improperly.
137    ///
138    /// # Safety
139    /// It is the caller's responsibility to ensure exclusivity and synchronization of the
140    /// instance before calling this function. No other pointers to any Instance data
141    /// should be dereferenced for the lifetime of the returned `&mut Instance`.
142    #[inline]
143    pub(super) unsafe fn as_mut_unchecked(&mut self) -> &mut Instance {
144        let ptr: *mut InstanceInner = Arc::as_ptr(&self.0) as *mut _;
145        (&mut *ptr).as_mut()
146    }
147}
148
149/// A weak instance ref. This type does not keep the underlying `Instance` alive
150/// but can be converted into a full `InstanceRef` if the underlying `Instance` hasn't
151/// been deallocated.
152#[derive(Debug, Clone)]
153pub struct WeakInstanceRef(Weak<InstanceInner>);
154
155impl PartialEq for WeakInstanceRef {
156    fn eq(&self, other: &Self) -> bool {
157        self.0.ptr_eq(&other.0)
158    }
159}
160
161impl WeakInstanceRef {
162    /// Try to convert into a strong, `InstanceRef`.
163    pub fn upgrade(&self) -> Option<InstanceRef> {
164        let inner = self.0.upgrade()?;
165        Some(InstanceRef(inner))
166    }
167}
168
169/// An `InstanceRef` that may or may not be keeping the `Instance` alive.
170///
171/// This type is useful for types that conditionally must keep / not keep the
172/// underlying `Instance` alive. For example, to prevent cycles in `WasmerEnv`s.
173#[derive(Debug, Clone, PartialEq)]
174pub enum WeakOrStrongInstanceRef {
175    /// A weak instance ref.
176    Weak(WeakInstanceRef),
177    /// A strong instance ref.
178    Strong(InstanceRef),
179}
180
181impl WeakOrStrongInstanceRef {
182    /// Tries to upgrade weak references to a strong reference, returning None
183    /// if it can't be done.
184    pub fn upgrade(&self) -> Option<Self> {
185        match self {
186            Self::Weak(weak) => weak.upgrade().map(Self::Strong),
187            Self::Strong(strong) => Some(Self::Strong(strong.clone())),
188        }
189    }
190
191    /// Clones self into a weak reference.
192    pub fn downgrade(&self) -> Self {
193        match self {
194            Self::Weak(weak) => Self::Weak(weak.clone()),
195            Self::Strong(strong) => Self::Weak(WeakInstanceRef(Arc::downgrade(&strong.0))),
196        }
197    }
198}
199
200impl TryFrom<WeakOrStrongInstanceRef> for InstanceRef {
201    type Error = &'static str;
202    fn try_from(value: WeakOrStrongInstanceRef) -> Result<Self, Self::Error> {
203        match value {
204            WeakOrStrongInstanceRef::Strong(strong) => Ok(strong),
205            WeakOrStrongInstanceRef::Weak(weak) => {
206                weak.upgrade().ok_or("Failed to upgrade weak reference")
207            }
208        }
209    }
210}
211
212impl From<WeakOrStrongInstanceRef> for WeakInstanceRef {
213    fn from(value: WeakOrStrongInstanceRef) -> Self {
214        match value {
215            WeakOrStrongInstanceRef::Strong(strong) => Self(Arc::downgrade(&strong.0)),
216            WeakOrStrongInstanceRef::Weak(weak) => weak,
217        }
218    }
219}
220
221impl From<WeakInstanceRef> for WeakOrStrongInstanceRef {
222    fn from(value: WeakInstanceRef) -> Self {
223        Self::Weak(value)
224    }
225}
226
227impl From<InstanceRef> for WeakOrStrongInstanceRef {
228    fn from(value: InstanceRef) -> Self {
229        Self::Strong(value)
230    }
231}