wasmer_compiler/artifact_builders/
artifact_builder.rs1#[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#[allow(unused)]
39use wasmer_types::*;
40
41#[cfg_attr(feature = "artifact-size", derive(loupe::MemoryUsage))]
43pub struct ArtifactBuild {
44 serializable: SerializableModule,
45}
46
47impl ArtifactBuild {
48 pub const MAGIC_HEADER: &'static [u8; 16] = b"wasmer-universal";
50
51 pub fn is_deserializable(bytes: &[u8]) -> bool {
53 bytes.starts_with(Self::MAGIC_HEADER)
54 }
55
56 #[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 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 let compilation = compiler.compile_module(
98 target,
99 &compile_info,
100 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 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 pub fn from_serializable(serializable: SerializableModule) -> Self {
158 Self { serializable }
159 }
160
161 pub fn get_function_bodies_ref(&self) -> &PrimaryMap<LocalFunctionIndex, FunctionBody> {
163 &self.serializable.compilation.function_bodies
164 }
165
166 pub fn get_function_call_trampolines_ref(&self) -> &PrimaryMap<SignatureIndex, FunctionBody> {
168 &self.serializable.compilation.function_call_trampolines
169 }
170
171 pub fn get_dynamic_function_trampolines_ref(&self) -> &PrimaryMap<FunctionIndex, FunctionBody> {
173 &self.serializable.compilation.dynamic_function_trampolines
174 }
175
176 pub fn get_custom_sections_ref(&self) -> &PrimaryMap<SectionIndex, CustomSection> {
178 &self.serializable.compilation.custom_sections
179 }
180
181 pub fn get_function_relocations(&self) -> &PrimaryMap<LocalFunctionIndex, Vec<Relocation>> {
183 &self.serializable.compilation.function_relocations
184 }
185
186 pub fn get_custom_section_relocations_ref(&self) -> &PrimaryMap<SectionIndex, Vec<Relocation>> {
188 &self.serializable.compilation.custom_section_relocations
189 }
190
191 pub fn get_libcall_trampolines(&self) -> SectionIndex {
193 self.serializable.compilation.libcall_trampolines
194 }
195
196 pub fn get_libcall_trampoline_len(&self) -> usize {
198 self.serializable.compilation.libcall_trampoline_len as usize
199 }
200
201 pub fn get_debug_ref(&self) -> Option<&Dwarf> {
203 self.serializable.compilation.debug.as_ref()
204 }
205
206 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#[derive(Debug)]
259pub struct ModuleFromArchive<'a> {
260 pub compilation: &'a ArchivedSerializableCompilation,
262 pub data_initializers: &'a rkyv::Archived<Box<[OwnedDataInitializer]>>,
264 pub cpu_features: u64,
266
267 original_module: &'a ArchivedSerializableModule,
269}
270
271impl<'a> ModuleFromArchive<'a> {
272 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#[derive(Clone, Debug)]
305#[cfg_attr(feature = "artifact-size", derive(loupe::MemoryUsage))]
306pub struct ArtifactBuildFromArchive {
307 cell: Arc<ArtifactBuildFromArchiveCell>,
308
309 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 let compile_info = unsafe { compile_info.assume_init() };
334 Ok(Self {
335 cell: Arc::new(cell),
336 compile_info,
337 })
338 }
339
340 pub fn owned_buffer(&self) -> &OwnedBuffer {
342 self.cell.borrow_owner()
343 }
344
345 pub fn get_function_bodies_ref(&self) -> &ArchivedPrimaryMap<LocalFunctionIndex, FunctionBody> {
347 &self.cell.borrow_dependent().compilation.function_bodies
348 }
349
350 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 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 pub fn get_custom_sections_ref(&self) -> &ArchivedPrimaryMap<SectionIndex, CustomSection> {
374 &self.cell.borrow_dependent().compilation.custom_sections
375 }
376
377 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 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 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 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 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 pub fn get_frame_info_ref(
428 &self,
429 ) -> &ArchivedPrimaryMap<LocalFunctionIndex, CompiledFunctionFrameInfo> {
430 &self.cell.borrow_dependent().compilation.function_frame_info
431 }
432
433 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 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}