wasmer_compiler/artifact_builders/
artifact_builder.rs

1//! Define `ArtifactBuild` to allow compiling and instantiating to be
2//! done as separate steps.
3
4#[cfg(feature = "compiler")]
5use super::trampoline::{libcall_trampoline_len, make_libcall_trampolines};
6
7#[cfg(feature = "compiler")]
8use crate::{
9    serialize::SerializableCompilation, types::target::Target, EngineInner, ModuleEnvironment,
10    ModuleMiddlewareChain,
11};
12use crate::{
13    serialize::{
14        ArchivedSerializableCompilation, ArchivedSerializableModule, MetadataHeader,
15        SerializableModule,
16    },
17    types::{
18        function::{CompiledFunctionFrameInfo, Dwarf, FunctionBody},
19        module::CompileModuleInfo,
20        relocation::Relocation,
21        section::{CustomSection, SectionIndex},
22        target::CpuFeature,
23    },
24    ArtifactCreate, Features,
25};
26use core::mem::MaybeUninit;
27use enumset::EnumSet;
28use rkyv::{option::ArchivedOption, rancor::Error as RkyvError};
29use self_cell::self_cell;
30use shared_buffer::OwnedBuffer;
31use std::sync::Arc;
32use wasmer_types::{
33    entity::{ArchivedPrimaryMap, PrimaryMap},
34    DeserializeError,
35};
36
37// Not every compiler backend uses these.
38#[allow(unused)]
39use wasmer_types::*;
40
41/// A compiled wasm module, ready to be instantiated.
42#[cfg_attr(feature = "artifact-size", derive(loupe::MemoryUsage))]
43pub struct ArtifactBuild {
44    serializable: SerializableModule,
45}
46
47impl ArtifactBuild {
48    /// Header signature for wasmu binary
49    pub const MAGIC_HEADER: &'static [u8; 16] = b"wasmer-universal";
50
51    /// Check if the provided bytes look like a serialized `ArtifactBuild`.
52    pub fn is_deserializable(bytes: &[u8]) -> bool {
53        bytes.starts_with(Self::MAGIC_HEADER)
54    }
55
56    /// Compile a data buffer into a `ArtifactBuild`, which may then be instantiated.
57    #[cfg(feature = "compiler")]
58    pub fn new(
59        inner_engine: &mut EngineInner,
60        data: &[u8],
61        target: &Target,
62        memory_styles: PrimaryMap<MemoryIndex, MemoryStyle>,
63        table_styles: PrimaryMap<TableIndex, TableStyle>,
64        hash_algorithm: Option<HashAlgorithm>,
65    ) -> Result<Self, CompileError> {
66        let environ = ModuleEnvironment::new();
67        let features = inner_engine.features().clone();
68
69        let translation = environ.translate(data).map_err(CompileError::Wasm)?;
70
71        let compiler = inner_engine.compiler()?;
72
73        // We try to apply the middleware first
74        let mut module = translation.module;
75        let middlewares = compiler.get_middlewares();
76        middlewares
77            .apply_on_module_info(&mut module)
78            .map_err(|err| CompileError::MiddlewareError(err.to_string()))?;
79
80        if let Some(hash_algorithm) = hash_algorithm {
81            let hash = match hash_algorithm {
82                HashAlgorithm::Sha256 => ModuleHash::sha256(data),
83                HashAlgorithm::XXHash => ModuleHash::xxhash(data),
84            };
85
86            module.hash = Some(hash);
87        }
88
89        let compile_info = CompileModuleInfo {
90            module: Arc::new(module),
91            features,
92            memory_styles,
93            table_styles,
94        };
95
96        // Compile the Module
97        let compilation = compiler.compile_module(
98            target,
99            &compile_info,
100            // SAFETY: Calling `unwrap` is correct since
101            // `environ.translate()` above will write some data into
102            // `module_translation_state`.
103            translation.module_translation_state.as_ref().unwrap(),
104            translation.function_body_inputs,
105        )?;
106
107        let data_initializers = translation
108            .data_initializers
109            .iter()
110            .map(OwnedDataInitializer::new)
111            .collect::<Vec<_>>()
112            .into_boxed_slice();
113
114        // Synthesize a custom section to hold the libcall trampolines.
115        let mut function_frame_info = PrimaryMap::with_capacity(compilation.functions.len());
116        let mut function_bodies = PrimaryMap::with_capacity(compilation.functions.len());
117        let mut function_relocations = PrimaryMap::with_capacity(compilation.functions.len());
118        for (_, func) in compilation.functions.into_iter() {
119            function_bodies.push(func.body);
120            function_relocations.push(func.relocations);
121            function_frame_info.push(func.frame_info);
122        }
123        let mut custom_sections = compilation.custom_sections.clone();
124        let mut custom_section_relocations = compilation
125            .custom_sections
126            .iter()
127            .map(|(_, section)| section.relocations.clone())
128            .collect::<PrimaryMap<SectionIndex, _>>();
129        let libcall_trampolines_section = make_libcall_trampolines(target);
130        custom_section_relocations.push(libcall_trampolines_section.relocations.clone());
131        let libcall_trampolines = custom_sections.push(libcall_trampolines_section);
132        let libcall_trampoline_len = libcall_trampoline_len(target) as u32;
133        let cpu_features = compiler.get_cpu_features_used(target.cpu_features());
134
135        let serializable_compilation = SerializableCompilation {
136            function_bodies,
137            function_relocations,
138            function_frame_info,
139            function_call_trampolines: compilation.function_call_trampolines,
140            dynamic_function_trampolines: compilation.dynamic_function_trampolines,
141            custom_sections,
142            custom_section_relocations,
143            debug: compilation.debug,
144            libcall_trampolines,
145            libcall_trampoline_len,
146        };
147        let serializable = SerializableModule {
148            compilation: serializable_compilation,
149            compile_info,
150            data_initializers,
151            cpu_features: cpu_features.as_u64(),
152        };
153        Ok(Self { serializable })
154    }
155
156    /// Create a new ArtifactBuild from a SerializableModule
157    pub fn from_serializable(serializable: SerializableModule) -> Self {
158        Self { serializable }
159    }
160
161    /// Get Functions Bodies ref
162    pub fn get_function_bodies_ref(&self) -> &PrimaryMap<LocalFunctionIndex, FunctionBody> {
163        &self.serializable.compilation.function_bodies
164    }
165
166    /// Get Functions Call Trampolines ref
167    pub fn get_function_call_trampolines_ref(&self) -> &PrimaryMap<SignatureIndex, FunctionBody> {
168        &self.serializable.compilation.function_call_trampolines
169    }
170
171    /// Get Dynamic Functions Call Trampolines ref
172    pub fn get_dynamic_function_trampolines_ref(&self) -> &PrimaryMap<FunctionIndex, FunctionBody> {
173        &self.serializable.compilation.dynamic_function_trampolines
174    }
175
176    /// Get Custom Sections ref
177    pub fn get_custom_sections_ref(&self) -> &PrimaryMap<SectionIndex, CustomSection> {
178        &self.serializable.compilation.custom_sections
179    }
180
181    /// Get Function Relocations
182    pub fn get_function_relocations(&self) -> &PrimaryMap<LocalFunctionIndex, Vec<Relocation>> {
183        &self.serializable.compilation.function_relocations
184    }
185
186    /// Get Function Relocations ref
187    pub fn get_custom_section_relocations_ref(&self) -> &PrimaryMap<SectionIndex, Vec<Relocation>> {
188        &self.serializable.compilation.custom_section_relocations
189    }
190
191    /// Get LibCall Trampoline Section Index
192    pub fn get_libcall_trampolines(&self) -> SectionIndex {
193        self.serializable.compilation.libcall_trampolines
194    }
195
196    /// Get LibCall Trampoline Length
197    pub fn get_libcall_trampoline_len(&self) -> usize {
198        self.serializable.compilation.libcall_trampoline_len as usize
199    }
200
201    /// Get Debug optional Dwarf ref
202    pub fn get_debug_ref(&self) -> Option<&Dwarf> {
203        self.serializable.compilation.debug.as_ref()
204    }
205
206    /// Get Function Relocations ref
207    pub fn get_frame_info_ref(&self) -> &PrimaryMap<LocalFunctionIndex, CompiledFunctionFrameInfo> {
208        &self.serializable.compilation.function_frame_info
209    }
210}
211
212impl<'a> ArtifactCreate<'a> for ArtifactBuild {
213    type OwnedDataInitializer = &'a OwnedDataInitializer;
214    type OwnedDataInitializerIterator = core::slice::Iter<'a, OwnedDataInitializer>;
215
216    fn create_module_info(&self) -> Arc<ModuleInfo> {
217        self.serializable.compile_info.module.clone()
218    }
219
220    fn set_module_info_name(&mut self, name: String) -> bool {
221        Arc::get_mut(&mut self.serializable.compile_info.module).map_or(false, |module_info| {
222            module_info.name = Some(name.to_string());
223            true
224        })
225    }
226
227    fn module_info(&self) -> &ModuleInfo {
228        &self.serializable.compile_info.module
229    }
230
231    fn features(&self) -> &Features {
232        &self.serializable.compile_info.features
233    }
234
235    fn cpu_features(&self) -> EnumSet<CpuFeature> {
236        EnumSet::from_u64(self.serializable.cpu_features)
237    }
238
239    fn data_initializers(&'a self) -> Self::OwnedDataInitializerIterator {
240        self.serializable.data_initializers.iter()
241    }
242
243    fn memory_styles(&self) -> &PrimaryMap<MemoryIndex, MemoryStyle> {
244        &self.serializable.compile_info.memory_styles
245    }
246
247    fn table_styles(&self) -> &PrimaryMap<TableIndex, TableStyle> {
248        &self.serializable.compile_info.table_styles
249    }
250
251    fn serialize(&self) -> Result<Vec<u8>, SerializeError> {
252        serialize_module(&self.serializable)
253    }
254}
255
256/// Module loaded from an archive. Since `CompileModuleInfo` is part of the public
257/// interface of this crate and has to be mutable, it has to be deserialized completely.
258#[derive(Debug)]
259pub struct ModuleFromArchive<'a> {
260    /// The main serializable compilation object
261    pub compilation: &'a ArchivedSerializableCompilation,
262    /// Datas initializers
263    pub data_initializers: &'a rkyv::Archived<Box<[OwnedDataInitializer]>>,
264    /// CPU Feature flags for this compilation
265    pub cpu_features: u64,
266
267    // Keep the original module around for re-serialization
268    original_module: &'a ArchivedSerializableModule,
269}
270
271impl<'a> ModuleFromArchive<'a> {
272    /// Create a new `ModuleFromArchive` from the archived version of a `SerializableModule`
273    pub fn from_serializable_module(
274        module: &'a ArchivedSerializableModule,
275    ) -> Result<Self, DeserializeError> {
276        Ok(Self {
277            compilation: &module.compilation,
278            data_initializers: &module.data_initializers,
279            cpu_features: module.cpu_features.to_native(),
280            original_module: module,
281        })
282    }
283}
284
285self_cell!(
286    struct ArtifactBuildFromArchiveCell {
287        owner: OwnedBuffer,
288
289        #[covariant]
290        dependent: ModuleFromArchive,
291    }
292
293    impl {Debug}
294);
295
296#[cfg(feature = "artifact-size")]
297impl loupe::MemoryUsage for ArtifactBuildFromArchiveCell {
298    fn size_of_val(&self, _tracker: &mut dyn loupe::MemoryUsageTracker) -> usize {
299        std::mem::size_of_val(self.borrow_owner()) + std::mem::size_of_val(self.borrow_dependent())
300    }
301}
302
303/// A compiled wasm module that was loaded from a serialized archive.
304#[derive(Clone, Debug)]
305#[cfg_attr(feature = "artifact-size", derive(loupe::MemoryUsage))]
306pub struct ArtifactBuildFromArchive {
307    cell: Arc<ArtifactBuildFromArchiveCell>,
308
309    /// Compilation informations
310    compile_info: CompileModuleInfo,
311}
312
313impl ArtifactBuildFromArchive {
314    #[allow(unused)]
315    pub(crate) fn try_new(
316        buffer: OwnedBuffer,
317        module_builder: impl FnOnce(
318            &OwnedBuffer,
319        ) -> Result<&ArchivedSerializableModule, DeserializeError>,
320    ) -> Result<Self, DeserializeError> {
321        let mut compile_info = MaybeUninit::uninit();
322
323        let cell = ArtifactBuildFromArchiveCell::try_new(buffer, |buffer| {
324            let module = module_builder(buffer)?;
325            compile_info = MaybeUninit::new(
326                rkyv::deserialize::<_, RkyvError>(&module.compile_info)
327                    .map_err(|e| DeserializeError::CorruptedBinary(format!("{:?}", e)))?,
328            );
329            ModuleFromArchive::from_serializable_module(module)
330        })?;
331
332        // Safety: we know the lambda will execute before getting here and assign both values
333        let compile_info = unsafe { compile_info.assume_init() };
334        Ok(Self {
335            cell: Arc::new(cell),
336            compile_info,
337        })
338    }
339
340    /// Gets the owned buffer
341    pub fn owned_buffer(&self) -> &OwnedBuffer {
342        self.cell.borrow_owner()
343    }
344
345    /// Get Functions Bodies ref
346    pub fn get_function_bodies_ref(&self) -> &ArchivedPrimaryMap<LocalFunctionIndex, FunctionBody> {
347        &self.cell.borrow_dependent().compilation.function_bodies
348    }
349
350    /// Get Functions Call Trampolines ref
351    pub fn get_function_call_trampolines_ref(
352        &self,
353    ) -> &ArchivedPrimaryMap<SignatureIndex, FunctionBody> {
354        &self
355            .cell
356            .borrow_dependent()
357            .compilation
358            .function_call_trampolines
359    }
360
361    /// Get Dynamic Functions Call Trampolines ref
362    pub fn get_dynamic_function_trampolines_ref(
363        &self,
364    ) -> &ArchivedPrimaryMap<FunctionIndex, FunctionBody> {
365        &self
366            .cell
367            .borrow_dependent()
368            .compilation
369            .dynamic_function_trampolines
370    }
371
372    /// Get Custom Sections ref
373    pub fn get_custom_sections_ref(&self) -> &ArchivedPrimaryMap<SectionIndex, CustomSection> {
374        &self.cell.borrow_dependent().compilation.custom_sections
375    }
376
377    /// Get Function Relocations
378    pub fn get_function_relocations(
379        &self,
380    ) -> &ArchivedPrimaryMap<LocalFunctionIndex, Vec<Relocation>> {
381        &self
382            .cell
383            .borrow_dependent()
384            .compilation
385            .function_relocations
386    }
387
388    /// Get Function Relocations ref
389    pub fn get_custom_section_relocations_ref(
390        &self,
391    ) -> &ArchivedPrimaryMap<SectionIndex, Vec<Relocation>> {
392        &self
393            .cell
394            .borrow_dependent()
395            .compilation
396            .custom_section_relocations
397    }
398
399    /// Get LibCall Trampoline Section Index
400    pub fn get_libcall_trampolines(&self) -> SectionIndex {
401        rkyv::deserialize::<_, RkyvError>(
402            &self.cell.borrow_dependent().compilation.libcall_trampolines,
403        )
404        .unwrap()
405    }
406
407    /// Get LibCall Trampoline Length
408    pub fn get_libcall_trampoline_len(&self) -> usize {
409        self.cell
410            .borrow_dependent()
411            .compilation
412            .libcall_trampoline_len
413            .to_native() as usize
414    }
415
416    /// Get Debug optional Dwarf ref
417    pub fn get_debug_ref(&self) -> Option<Dwarf> {
418        match self.cell.borrow_dependent().compilation.debug {
419            ArchivedOption::Some(ref x) => {
420                Some(rkyv::deserialize::<_, rkyv::rancor::Error>(x).unwrap())
421            }
422            ArchivedOption::None => None,
423        }
424    }
425
426    /// Get Function Relocations ref
427    pub fn get_frame_info_ref(
428        &self,
429    ) -> &ArchivedPrimaryMap<LocalFunctionIndex, CompiledFunctionFrameInfo> {
430        &self.cell.borrow_dependent().compilation.function_frame_info
431    }
432
433    /// Get Function Relocations ref
434    pub fn deserialize_frame_info_ref(
435        &self,
436    ) -> Result<PrimaryMap<LocalFunctionIndex, CompiledFunctionFrameInfo>, DeserializeError> {
437        rkyv::deserialize::<_, RkyvError>(
438            &self.cell.borrow_dependent().compilation.function_frame_info,
439        )
440        .map_err(|e| DeserializeError::CorruptedBinary(format!("{:?}", e)))
441    }
442}
443
444impl<'a> ArtifactCreate<'a> for ArtifactBuildFromArchive {
445    type OwnedDataInitializer = &'a ArchivedOwnedDataInitializer;
446    type OwnedDataInitializerIterator = core::slice::Iter<'a, ArchivedOwnedDataInitializer>;
447
448    fn create_module_info(&self) -> Arc<ModuleInfo> {
449        self.compile_info.module.clone()
450    }
451
452    fn set_module_info_name(&mut self, name: String) -> bool {
453        Arc::get_mut(&mut self.compile_info.module).map_or(false, |module_info| {
454            module_info.name = Some(name.to_string());
455            true
456        })
457    }
458
459    fn module_info(&self) -> &ModuleInfo {
460        &self.compile_info.module
461    }
462
463    fn features(&self) -> &Features {
464        &self.compile_info.features
465    }
466
467    fn cpu_features(&self) -> EnumSet<CpuFeature> {
468        EnumSet::from_u64(self.cell.borrow_dependent().cpu_features)
469    }
470
471    fn data_initializers(&'a self) -> Self::OwnedDataInitializerIterator {
472        self.cell.borrow_dependent().data_initializers.iter()
473    }
474
475    fn memory_styles(&self) -> &PrimaryMap<MemoryIndex, MemoryStyle> {
476        &self.compile_info.memory_styles
477    }
478
479    fn table_styles(&self) -> &PrimaryMap<TableIndex, TableStyle> {
480        &self.compile_info.table_styles
481    }
482
483    fn serialize(&self) -> Result<Vec<u8>, SerializeError> {
484        // We could have stored the original bytes, but since the module info name
485        // is mutable, we have to assume the data may have changed and serialize
486        // everything all over again. Also, to be able to serialize, first we have
487        // to deserialize completely. Luckily, serializing a module that was already
488        // deserialized from a file makes little sense, so hopefully, this is not a
489        // common use-case.
490
491        let mut module: SerializableModule =
492            rkyv::deserialize::<_, RkyvError>(self.cell.borrow_dependent().original_module)
493                .map_err(|e| SerializeError::Generic(e.to_string()))?;
494        module.compile_info = self.compile_info.clone();
495        serialize_module(&module)
496    }
497}
498
499fn serialize_module(module: &SerializableModule) -> Result<Vec<u8>, SerializeError> {
500    let serialized_data = module.serialize()?;
501    assert!(std::mem::align_of::<SerializableModule>() <= MetadataHeader::ALIGN);
502
503    let mut metadata_binary = vec![];
504    metadata_binary.extend(ArtifactBuild::MAGIC_HEADER);
505    metadata_binary.extend(MetadataHeader::new(serialized_data.len()).into_bytes());
506    metadata_binary.extend(serialized_data);
507    Ok(metadata_binary)
508}