wasmer/entities/store/
mod.rs

1//! Defines the [`Store`] data type and various useful traits and data types to interact with a
2//! store.
3
4/// Defines the [`AsStoreAsync`] trait and its supporting types.
5#[cfg(feature = "experimental-async")]
6mod async_;
7#[cfg(feature = "experimental-async")]
8pub use async_::*;
9
10/// Defines the [`StoreContext`] type.
11mod context;
12
13/// Defines the [`StoreInner`] data type.
14mod inner;
15
16/// Create temporary handles to engines.
17mod store_ref;
18
19/// Single-threaded async-aware RwLock.
20#[cfg(feature = "experimental-async")]
21mod local_rwlock;
22#[cfg(feature = "experimental-async")]
23pub(crate) use local_rwlock::*;
24
25use std::{
26    boxed::Box,
27    ops::{Deref, DerefMut},
28};
29
30pub use store_ref::*;
31
32mod obj;
33pub use obj::*;
34
35use crate::{AsEngineRef, BackendEngine, Engine, EngineRef};
36pub(crate) use context::*;
37pub(crate) use inner::*;
38use wasmer_types::StoreId;
39
40#[cfg(feature = "sys")]
41use wasmer_vm::TrapHandlerFn;
42
43/// The store represents all global state that can be manipulated by
44/// WebAssembly programs. It consists of the runtime representation
45/// of all instances of functions, tables, memories, and globals that
46/// have been allocated during the lifetime of the abstract machine.
47///
48/// The [`Store`] is tied to the underlying [`Engine`] that is — among many things — used to
49/// compile the Wasm bytes into a valid module artifact.
50///
51/// For more informations, check out the [related WebAssembly specification]
52/// [related WebAssembly specification]: <https://webassembly.github.io/spec/core/exec/runtime.html#store>
53pub struct Store {
54    pub(crate) inner: Box<StoreInner>,
55}
56
57impl Store {
58    /// Creates a new `Store` with a specific [`Engine`].
59    pub fn new(engine: impl Into<Engine>) -> Self {
60        let engine: Engine = engine.into();
61
62        let store = match engine.be {
63            #[cfg(feature = "sys")]
64            BackendEngine::Sys(_) => {
65                BackendStore::Sys(crate::backend::sys::entities::store::Store::new(engine))
66            }
67            #[cfg(feature = "wamr")]
68            BackendEngine::Wamr(_) => {
69                BackendStore::Wamr(crate::backend::wamr::entities::store::Store::new(engine))
70            }
71            #[cfg(feature = "wasmi")]
72            BackendEngine::Wasmi(_) => {
73                BackendStore::Wasmi(crate::backend::wasmi::entities::store::Store::new(engine))
74            }
75            #[cfg(feature = "v8")]
76            BackendEngine::V8(_) => {
77                BackendStore::V8(crate::backend::v8::entities::store::Store::new(engine))
78            }
79            #[cfg(feature = "js")]
80            BackendEngine::Js(_) => {
81                BackendStore::Js(crate::backend::js::entities::store::Store::new(engine))
82            }
83            #[cfg(feature = "jsc")]
84            BackendEngine::Jsc(_) => {
85                BackendStore::Jsc(crate::backend::jsc::entities::store::Store::new(engine))
86            }
87        };
88
89        Self {
90            inner: Box::new(StoreInner {
91                objects: StoreObjects::from_store_ref(&store),
92                on_called: None,
93                store,
94            }),
95        }
96    }
97
98    #[cfg(feature = "sys")]
99    /// Set the [`TrapHandlerFn`] for this store.
100    ///
101    /// # Note
102    ///
103    /// Not every implementor allows changing the trap handler. In those store that
104    /// don't allow it, this function has no effect.
105    pub fn set_trap_handler(&mut self, handler: Option<Box<TrapHandlerFn<'static>>>) {
106        use crate::backend::sys::entities::store::NativeStoreExt;
107        #[allow(irrefutable_let_patterns)]
108        if let BackendStore::Sys(ref mut s) = self.inner.store {
109            s.set_trap_handler(handler)
110        }
111    }
112
113    /// Returns the [`Engine`].
114    pub fn engine(&self) -> &Engine {
115        self.inner.store.engine()
116    }
117
118    /// Returns mutable reference to [`Engine`].
119    pub fn engine_mut(&mut self) -> &mut Engine {
120        self.inner.store.engine_mut()
121    }
122
123    /// Checks whether two stores are identical. A store is considered
124    /// equal to another store if both have the same engine.
125    pub fn same(a: &Self, b: &Self) -> bool {
126        a.id() == b.id()
127    }
128
129    /// Returns the ID of this store
130    pub fn id(&self) -> StoreId {
131        self.inner.objects.id()
132    }
133
134    /// Builds an [`Interrupter`] for this store. Calling [`Interrupter::interrupt`]
135    /// will cause running WASM code to terminate immediately with a
136    /// [`HostInterrupt`](crate::backend::sys::vm::TrapCode::HostInterrupt) trap.
137    ///
138    /// Best effort is made to ensure interrupts are handled. However, there is no
139    /// guarantee; under rare circumstances, it is possible for the interrupt to be
140    /// missed. One such case is when the target thread is about to call WASM code
141    /// but has not yet made the call.
142    ///
143    /// To make sure the code is interrupted, the target thread should notify
144    /// the signalling thread that it has finished running in some way, and
145    /// the signalling thread must wait for that notification and retry the
146    /// interrupt if the notification is not received after some time. Embedders
147    /// are expected to implement this logic.
148    ///
149    /// If an interrupt is delivered while an imported function is running,
150    /// the interrupt will simply be stored and processed only when the
151    /// imported function returns control to WASM code. No effort is made
152    /// to interrupt running imported functions. Embedders are expected to
153    /// implement support for interruption of long-running or blocking
154    /// imported functions separately.
155    #[cfg(all(unix, feature = "experimental-host-interrupt"))]
156    pub fn interrupter(&self) -> Interrupter {
157        self.inner.objects.interrupter()
158    }
159
160    #[cfg(feature = "experimental-async")]
161    /// Transforms this store into a [`StoreAsync`] which can be used
162    /// to invoke [`Function::call_async`](crate::Function::call_async).
163    pub fn into_async(self) -> StoreAsync {
164        StoreAsync {
165            id: self.id(),
166            inner: LocalRwLock::new(self.inner),
167        }
168    }
169}
170
171impl PartialEq for Store {
172    fn eq(&self, other: &Self) -> bool {
173        Self::same(self, other)
174    }
175}
176
177// This is required to be able to set the trap_handler in the
178// Store.
179unsafe impl Send for Store {}
180unsafe impl Sync for Store {}
181
182impl Default for Store {
183    fn default() -> Self {
184        Self::new(Engine::default())
185    }
186}
187
188impl std::fmt::Debug for Store {
189    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
190        f.debug_struct("Store").finish()
191    }
192}
193
194impl AsEngineRef for Store {
195    fn as_engine_ref(&self) -> EngineRef<'_> {
196        self.inner.store.as_engine_ref()
197    }
198
199    fn maybe_as_store(&self) -> Option<StoreRef<'_>> {
200        Some(self.as_store_ref())
201    }
202}
203
204impl AsStoreRef for Store {
205    fn as_store_ref(&self) -> StoreRef<'_> {
206        StoreRef { inner: &self.inner }
207    }
208}
209impl AsStoreMut for Store {
210    fn as_store_mut(&mut self) -> StoreMut<'_> {
211        StoreMut {
212            inner: &mut self.inner,
213        }
214    }
215
216    fn objects_mut(&mut self) -> &mut StoreObjects {
217        &mut self.inner.objects
218    }
219}