Skip to main content

wasmer_artifact/
artifact.rs

1use crate::{DeserializeError, SerializeError};
2use enumset::EnumSet;
3use loupe::MemoryUsage;
4use std::any::Any;
5use std::convert::TryInto;
6use std::path::Path;
7use std::sync::Arc;
8use std::{fs, mem};
9use wasmer_compiler::{CpuFeature, Features};
10use wasmer_types::entity::PrimaryMap;
11use wasmer_types::{
12    MemoryIndex, MemoryStyle, ModuleInfo, OwnedDataInitializer, TableIndex, TableStyle,
13};
14
15/// An `Artifact` is the product that the `Engine`
16/// implementation produce and use.
17///
18/// The `Artifact` contains the compiled data for a given
19/// module as well as extra information needed to run the
20/// module at runtime, such as [`ModuleInfo`] and [`Features`].
21pub trait ArtifactCreate: Send + Sync + Upcastable + MemoryUsage {
22    /// Return a reference-counted pointer to the module
23    fn module(&self) -> Arc<ModuleInfo>;
24
25    /// Return a pointer to a module.
26    fn module_ref(&self) -> &ModuleInfo;
27
28    /// Gets a mutable reference to the info.
29    ///
30    /// Note: this will return `None` if the module is already instantiated.
31    fn module_mut(&mut self) -> Option<&mut ModuleInfo>;
32
33    /// Returns the features for this Artifact
34    fn features(&self) -> &Features;
35
36    /// Returns the CPU features for this Artifact
37    fn cpu_features(&self) -> EnumSet<CpuFeature>;
38
39    /// Returns the memory styles associated with this `Artifact`.
40    fn memory_styles(&self) -> &PrimaryMap<MemoryIndex, MemoryStyle>;
41
42    /// Returns the table plans associated with this `Artifact`.
43    fn table_styles(&self) -> &PrimaryMap<TableIndex, TableStyle>;
44
45    /// Returns data initializers to pass to `InstanceHandle::initialize`
46    fn data_initializers(&self) -> &[OwnedDataInitializer];
47
48    /// Serializes an artifact into bytes
49    fn serialize(&self) -> Result<Vec<u8>, SerializeError>;
50
51    /// Serializes an artifact into a file path
52    fn serialize_to_file(&self, path: &Path) -> Result<(), SerializeError> {
53        let serialized = self.serialize()?;
54        fs::write(&path, serialized)?;
55        Ok(())
56    }
57}
58
59// Implementation of `Upcastable` taken from https://users.rust-lang.org/t/why-does-downcasting-not-work-for-subtraits/33286/7 .
60/// Trait needed to get downcasting of `Engine`s to work.
61pub trait Upcastable {
62    /// upcast ref
63    fn upcast_any_ref(&'_ self) -> &'_ dyn Any;
64    /// upcast mut ref
65    fn upcast_any_mut(&'_ mut self) -> &'_ mut dyn Any;
66    /// upcast boxed dyn
67    fn upcast_any_box(self: Box<Self>) -> Box<dyn Any>;
68}
69
70impl<T: Any + Send + Sync + 'static> Upcastable for T {
71    #[inline]
72    fn upcast_any_ref(&'_ self) -> &'_ dyn Any {
73        self
74    }
75    #[inline]
76    fn upcast_any_mut(&'_ mut self) -> &'_ mut dyn Any {
77        self
78    }
79    #[inline]
80    fn upcast_any_box(self: Box<Self>) -> Box<dyn Any> {
81        self
82    }
83}
84
85impl dyn ArtifactCreate + 'static {
86    /// Try to downcast the artifact into a given type.
87    #[inline]
88    pub fn downcast_ref<T: 'static>(&'_ self) -> Option<&'_ T> {
89        self.upcast_any_ref().downcast_ref::<T>()
90    }
91
92    /// Try to downcast the artifact into a given type mutably.
93    #[inline]
94    pub fn downcast_mut<T: 'static>(&'_ mut self) -> Option<&'_ mut T> {
95        self.upcast_any_mut().downcast_mut::<T>()
96    }
97}
98
99/// Metadata header which holds an ABI version and the length of the remaining
100/// metadata.
101#[repr(C)]
102#[derive(Clone, Copy)]
103pub struct MetadataHeader {
104    magic: [u8; 8],
105    version: u32,
106    len: u32,
107}
108
109impl MetadataHeader {
110    /// Current ABI version. Increment this any time breaking changes are made
111    /// to the format of the serialized data.
112    const CURRENT_VERSION: u32 = 1;
113
114    /// Magic number to identify wasmer metadata.
115    const MAGIC: [u8; 8] = *b"WASMER\0\0";
116
117    /// Length of the metadata header.
118    pub const LEN: usize = 16;
119
120    /// Alignment of the metadata.
121    pub const ALIGN: usize = 16;
122
123    /// Creates a new header for metadata of the given length.
124    pub fn new(len: usize) -> [u8; 16] {
125        let header = MetadataHeader {
126            magic: Self::MAGIC,
127            version: Self::CURRENT_VERSION,
128            len: len.try_into().expect("metadata exceeds maximum length"),
129        };
130        unsafe { mem::transmute(header) }
131    }
132
133    /// Parses the header and returns the length of the metadata following it.
134    pub fn parse(bytes: &[u8]) -> Result<usize, DeserializeError> {
135        if bytes.as_ptr() as usize % 16 != 0 {
136            return Err(DeserializeError::CorruptedBinary(
137                "misaligned metadata".to_string(),
138            ));
139        }
140        let bytes: [u8; 16] = bytes
141            .get(..16)
142            .ok_or_else(|| {
143                DeserializeError::CorruptedBinary("invalid metadata header".to_string())
144            })?
145            .try_into()
146            .unwrap();
147        let header: MetadataHeader = unsafe { mem::transmute(bytes) };
148        if header.magic != Self::MAGIC {
149            return Err(DeserializeError::Incompatible(
150                "The provided bytes were not serialized by Wasmer".to_string(),
151            ));
152        }
153        if header.version != Self::CURRENT_VERSION {
154            return Err(DeserializeError::Incompatible(
155                "The provided bytes were serialized by an incompatible version of Wasmer"
156                    .to_string(),
157            ));
158        }
159        Ok(header.len as usize)
160    }
161}