1#[cfg(feature = "unwind")]
4use crate::dwarf::WriterRelocate;
5
6#[cfg(feature = "unwind")]
7use crate::eh::{FunctionLsdaData, build_function_lsda, build_lsda_section, build_tag_section};
8
9#[cfg(feature = "unwind")]
10use crate::translator::CraneliftUnwindInfo;
11use crate::{
12 address_map::get_function_address_map,
13 config::Cranelift,
14 func_environ::{FuncEnvironment, get_function_name},
15 trampoline::{
16 FunctionBuilderContext, make_trampoline_dynamic_function, make_trampoline_function_call,
17 },
18 translator::{
19 FuncTranslator, compiled_function_unwind_info, irlibcall_to_libcall,
20 irreloc_to_relocationkind, signature_to_cranelift_ir,
21 },
22};
23use cranelift_codegen::{
24 Context, FinalizedMachReloc, FinalizedRelocTarget, MachTrap,
25 ir::{self, ExternalName, UserFuncName},
26};
27
28#[cfg(feature = "unwind")]
29use gimli::{
30 constants::DW_EH_PE_absptr,
31 write::{Address, EhFrame, FrameDescriptionEntry, FrameTable, Writer},
32};
33
34#[cfg(feature = "rayon")]
35use rayon::prelude::{IntoParallelRefIterator, ParallelIterator};
36#[cfg(feature = "unwind")]
37use std::collections::HashMap;
38use std::sync::Arc;
39use wasmer_compiler::WASM_TRAMPOLINE_ESTIMATED_BODY_SIZE;
40
41use wasmer_compiler::progress::ProgressContext;
42#[cfg(feature = "unwind")]
43use wasmer_compiler::types::{section::SectionIndex, unwind::CompiledFunctionUnwindInfo};
44use wasmer_compiler::{
45 Compiler, FunctionBinaryReader, FunctionBodyData, MiddlewareBinaryReader, ModuleMiddleware,
46 ModuleMiddlewareChain, ModuleTranslationState,
47 types::{
48 function::{
49 Compilation, CompiledFunction, CompiledFunctionFrameInfo, FunctionBody, UnwindInfo,
50 },
51 module::CompileModuleInfo,
52 relocation::{Relocation, RelocationTarget},
53 },
54};
55#[cfg(feature = "rayon")]
56use wasmer_compiler::{build_function_buckets, translate_function_buckets};
57#[cfg(feature = "unwind")]
58use wasmer_types::entity::EntityRef;
59use wasmer_types::entity::PrimaryMap;
60#[cfg(feature = "unwind")]
61use wasmer_types::target::CallingConvention;
62use wasmer_types::target::Target;
63use wasmer_types::{
64 CompilationProgressCallback, CompileError, FunctionIndex, LocalFunctionIndex, ModuleInfo,
65 SignatureIndex, TrapCode, TrapInformation,
66};
67
68pub struct CraneliftCompiledFunction {
69 function: CompiledFunction,
70 #[cfg(feature = "unwind")]
71 fde: Option<FrameDescriptionEntry>,
72 #[cfg(feature = "unwind")]
73 function_lsda: Option<FunctionLsdaData>,
74}
75
76impl wasmer_compiler::CompiledFunction for CraneliftCompiledFunction {}
77
78#[derive(Debug)]
81pub struct CraneliftCompiler {
82 config: Cranelift,
83}
84
85impl CraneliftCompiler {
86 pub fn new(config: Cranelift) -> Self {
88 Self { config }
89 }
90
91 pub fn config(&self) -> &Cranelift {
93 &self.config
94 }
95
96 fn compile_module_internal(
99 &self,
100 target: &Target,
101 compile_info: &CompileModuleInfo,
102 module_translation_state: &ModuleTranslationState,
103 function_body_inputs: PrimaryMap<LocalFunctionIndex, FunctionBodyData<'_>>,
104 progress_callback: Option<&CompilationProgressCallback>,
105 ) -> Result<Compilation, CompileError> {
106 let isa = self
107 .config()
108 .isa(target)
109 .map_err(|error| CompileError::Codegen(error.to_string()))?;
110 let frontend_config = isa.frontend_config();
111 #[cfg(feature = "unwind")]
112 let pointer_bytes = frontend_config.pointer_bytes();
113 let memory_styles = &compile_info.memory_styles;
114 let table_styles = &compile_info.table_styles;
115 let module = &compile_info.module;
116 let signatures = module
117 .signatures
118 .iter()
119 .map(|(_sig_index, func_type)| signature_to_cranelift_ir(func_type, frontend_config))
120 .collect::<PrimaryMap<SignatureIndex, ir::Signature>>();
121 let signature_hashes = &module.signature_hashes;
122
123 let total_function_call_trampolines = module.signatures.len();
124 let total_dynamic_trampolines = module.num_imported_functions;
125 let total_steps = WASM_TRAMPOLINE_ESTIMATED_BODY_SIZE
126 * ((total_dynamic_trampolines + total_function_call_trampolines) as u64)
127 + function_body_inputs
128 .iter()
129 .map(|(_, body)| body.data.len() as u64)
130 .sum::<u64>();
131 let progress = progress_callback
132 .cloned()
133 .map(|cb| ProgressContext::new(cb, total_steps, "cranelift::functions"));
134
135 #[cfg(feature = "unwind")]
137 let dwarf_frametable = if function_body_inputs.is_empty() {
138 None
142 } else {
143 match target.triple().default_calling_convention() {
144 Ok(CallingConvention::SystemV) => match isa.create_systemv_cie() {
145 Some(mut cie) => {
146 cie.personality = Some((
147 DW_EH_PE_absptr,
148 Address::Symbol {
149 symbol: WriterRelocate::PERSONALITY_SYMBOL,
150 addend: 0,
151 },
152 ));
153 cie.lsda_encoding = Some(DW_EH_PE_absptr);
154 let mut dwarf_frametable = FrameTable::default();
155 let cie_id = dwarf_frametable.add_cie(cie);
156 Some((dwarf_frametable, cie_id))
157 }
158 None => None,
160 },
161 _ => None,
162 }
163 };
164
165 let compile_function = |func_translator: &mut FuncTranslator,
168 i: &LocalFunctionIndex,
169 input: &FunctionBodyData|
170 -> Result<CraneliftCompiledFunction, CompileError> {
171 let func_index = module.func_index(*i);
172 let mut context = Context::new();
173 let mut func_env = FuncEnvironment::new(
174 isa.frontend_config(),
175 module,
176 &signatures,
177 signature_hashes,
178 memory_styles,
179 table_styles,
180 );
181 context.func.name = match get_function_name(&mut context.func, func_index) {
182 ExternalName::User(nameref) => {
183 if context.func.params.user_named_funcs().is_valid(nameref) {
184 let name = &context.func.params.user_named_funcs()[nameref];
185 UserFuncName::User(name.clone())
186 } else {
187 UserFuncName::default()
188 }
189 }
190 ExternalName::TestCase(testcase) => UserFuncName::Testcase(testcase),
191 _ => UserFuncName::default(),
192 };
193 context.func.signature = signatures[module.functions[func_index]].clone();
194 let mut reader =
199 MiddlewareBinaryReader::new_with_offset(input.data, input.module_offset);
200 reader.set_middleware_chain(
201 self.config
202 .middlewares
203 .generate_function_middleware_chain(*i),
204 );
205
206 func_translator.translate(
207 module_translation_state,
208 &mut reader,
209 &mut context.func,
210 &mut func_env,
211 *i,
212 )?;
213
214 if let Some(callbacks) = self.config.callbacks.as_ref() {
215 use wasmer_compiler::misc::CompiledKind;
216
217 callbacks.preopt_ir(
218 &CompiledKind::Local(*i, compile_info.module.get_function_name(func_index)),
219 &compile_info.module.hash_string(),
220 context.func.display().to_string().as_bytes(),
221 );
222 }
223
224 let mut code_buf: Vec<u8> = Vec::new();
225 let mut ctrl_plane = Default::default();
226 let func_name_map = context.func.params.user_named_funcs().clone();
227 let result = context
228 .compile(&*isa, &mut ctrl_plane)
229 .map_err(|error| CompileError::Codegen(format!("{error:#?}")))?;
230 code_buf.extend_from_slice(result.code_buffer());
231
232 if let Some(callbacks) = self.config.callbacks.as_ref() {
233 use wasmer_compiler::misc::CompiledKind;
234
235 callbacks.obj_memory_buffer(
236 &CompiledKind::Local(*i, compile_info.module.get_function_name(func_index)),
237 &compile_info.module.hash_string(),
238 &code_buf,
239 );
240 callbacks.asm_memory_buffer(
241 &CompiledKind::Local(*i, compile_info.module.get_function_name(func_index)),
242 &compile_info.module.hash_string(),
243 target.triple().architecture,
244 &code_buf,
245 )?;
246 }
247
248 let func_relocs = result
249 .buffer
250 .relocs()
251 .iter()
252 .map(|r| mach_reloc_to_reloc(module, &func_name_map, r))
253 .collect::<Vec<_>>();
254
255 let traps = result
256 .buffer
257 .traps()
258 .iter()
259 .map(mach_trap_to_trap)
260 .collect::<Vec<_>>();
261
262 #[cfg(feature = "unwind")]
263 let function_lsda = if dwarf_frametable.is_some() {
264 build_function_lsda(
265 result.buffer.call_sites(),
266 result.buffer.data().len(),
267 pointer_bytes,
268 )
269 } else {
270 None
271 };
272
273 #[allow(unused)]
274 let (unwind_info, fde) = match compiled_function_unwind_info(&*isa, &context)? {
275 #[cfg(feature = "unwind")]
276 CraneliftUnwindInfo::Fde(fde) => {
277 if dwarf_frametable.is_some() {
278 let fde = fde.to_fde(Address::Symbol {
279 symbol: WriterRelocate::FUNCTION_SYMBOL,
282 addend: i.index() as _,
285 });
286 (Some(CompiledFunctionUnwindInfo::Dwarf), Some(fde))
288 } else {
289 (None, None)
290 }
291 }
292 #[cfg(feature = "unwind")]
293 other => (other.maybe_into_to_windows_unwind(), None),
294
295 #[cfg(not(feature = "unwind"))]
298 other => (other.maybe_into_to_windows_unwind(), None::<()>),
299 };
300
301 let range = reader.range();
302 let address_map = get_function_address_map(&context, range, code_buf.len());
303
304 Ok(CraneliftCompiledFunction {
305 function: CompiledFunction {
306 body: FunctionBody {
307 body: code_buf,
308 unwind_info,
309 },
310 relocations: func_relocs,
311 frame_info: CompiledFunctionFrameInfo { address_map, traps },
312 },
313 #[cfg(feature = "unwind")]
314 fde,
315 #[cfg(feature = "unwind")]
316 function_lsda,
317 })
318 };
319
320 #[cfg_attr(not(feature = "unwind"), allow(unused_mut))]
321 let mut custom_sections = PrimaryMap::new();
322
323 #[cfg(not(feature = "rayon"))]
324 let mut func_translator = FuncTranslator::new();
325 #[cfg(not(feature = "rayon"))]
326 let results = function_body_inputs
327 .iter()
328 .collect::<Vec<(LocalFunctionIndex, &FunctionBodyData<'_>)>>()
329 .into_iter()
330 .map(|(i, input)| {
331 let result = compile_function(&mut func_translator, &i, input)?;
332 if let Some(progress) = progress.as_ref() {
333 progress.notify_steps(input.data.len() as u64)?;
334 }
335 Ok(result)
336 })
337 .collect::<Result<Vec<_>, CompileError>>()?;
338 #[cfg(feature = "rayon")]
339 let results = {
340 use wasmer_compiler::WASM_LARGE_FUNCTION_THRESHOLD;
341
342 let buckets =
343 build_function_buckets(&function_body_inputs, WASM_LARGE_FUNCTION_THRESHOLD / 3);
344 let largest_bucket = buckets.first().map(|b| b.size).unwrap_or_default();
345 tracing::debug!(buckets = buckets.len(), largest_bucket, "buckets built");
346 let num_threads = self.config.num_threads.get();
347 let pool = rayon::ThreadPoolBuilder::new()
348 .num_threads(num_threads)
349 .build()
350 .unwrap();
351
352 translate_function_buckets(
353 &pool,
354 FuncTranslator::new,
355 |func_translator, i, input| compile_function(func_translator, i, input),
356 progress.clone(),
357 &buckets,
358 )?
359 };
360
361 let mut functions = Vec::with_capacity(function_body_inputs.len());
362 #[cfg(feature = "unwind")]
363 let mut fdes = Vec::with_capacity(function_body_inputs.len());
364 #[cfg(feature = "unwind")]
365 let mut lsda_data = Vec::with_capacity(function_body_inputs.len());
366
367 for compiled in results {
368 let CraneliftCompiledFunction {
369 function,
370 #[cfg(feature = "unwind")]
371 fde,
372 #[cfg(feature = "unwind")]
373 function_lsda,
374 } = compiled;
375 functions.push(function);
376 #[cfg(feature = "unwind")]
377 {
378 fdes.push(fde);
379 lsda_data.push(function_lsda);
380 }
381 }
382
383 #[cfg(feature = "unwind")]
384 let (_tag_section_index, lsda_section_index, function_lsda_offsets) =
385 if dwarf_frametable.is_some() {
386 let mut tag_section_index = None;
387 let mut tag_offsets = HashMap::new();
388 if let Some((tag_section, offsets)) = build_tag_section(&lsda_data) {
389 custom_sections.push(tag_section);
390 tag_section_index = Some(SectionIndex::new(custom_sections.len() - 1));
391 tag_offsets = offsets;
392 }
393 let lsda_vec = lsda_data;
394 let (lsda_section, offsets_per_function) =
395 build_lsda_section(lsda_vec, pointer_bytes, &tag_offsets, tag_section_index);
396 let mut lsda_section_index = None;
397 if let Some(section) = lsda_section {
398 custom_sections.push(section);
399 lsda_section_index = Some(SectionIndex::new(custom_sections.len() - 1));
400 }
401 (tag_section_index, lsda_section_index, offsets_per_function)
402 } else {
403 (None, None, vec![None; functions.len()])
404 };
405
406 #[cfg_attr(not(feature = "unwind"), allow(unused_mut))]
407 let mut unwind_info = UnwindInfo::default();
408
409 #[cfg(feature = "unwind")]
410 if let Some((mut dwarf_frametable, cie_id)) = dwarf_frametable {
411 for (func_idx, fde_opt) in fdes.into_iter().enumerate() {
412 if let Some(mut fde) = fde_opt {
413 let has_lsda = function_lsda_offsets
414 .get(func_idx)
415 .and_then(|v| *v)
416 .is_some();
417 let lsda_address = if has_lsda {
418 debug_assert!(
419 lsda_section_index.is_some(),
420 "LSDA offsets require an LSDA section"
421 );
422 if lsda_section_index.is_some() {
423 let symbol =
424 WriterRelocate::lsda_symbol(LocalFunctionIndex::new(func_idx));
425 Address::Symbol { symbol, addend: 0 }
426 } else {
427 Address::Constant(0)
428 }
429 } else {
430 Address::Constant(0)
431 };
432 fde.lsda = Some(lsda_address);
433 dwarf_frametable.add_fde(cie_id, fde);
434 }
435 }
436
437 let mut writer = WriterRelocate::new(target.triple().endianness().ok());
438 if let Some(lsda_section_index) = lsda_section_index {
439 for (func_idx, offset) in function_lsda_offsets.iter().enumerate() {
440 if let Some(offset) = offset {
441 writer.register_lsda_symbol(
442 WriterRelocate::lsda_symbol(LocalFunctionIndex::new(func_idx)),
443 RelocationTarget::CustomSection(lsda_section_index),
444 *offset,
445 );
446 }
447 }
448 }
449
450 let mut eh_frame = EhFrame(writer);
451 dwarf_frametable.write_eh_frame(&mut eh_frame).unwrap();
452 eh_frame.write(&[0, 0, 0, 0]).unwrap(); let eh_frame_section = eh_frame.0.into_section();
455 custom_sections.push(eh_frame_section);
456 unwind_info.eh_frame = Some(SectionIndex::new(custom_sections.len() - 1));
457 };
458
459 let module_hash = module.hash_string();
460
461 #[cfg(not(feature = "rayon"))]
463 let mut cx = FunctionBuilderContext::new();
464 #[cfg(not(feature = "rayon"))]
465 let function_call_trampolines = module
466 .signatures
467 .values()
468 .collect::<Vec<_>>()
469 .into_iter()
470 .map(|sig| {
471 let trampoline = make_trampoline_function_call(
472 &self.config().callbacks,
473 &*isa,
474 target.triple().architecture,
475 &mut cx,
476 sig,
477 &module_hash,
478 )?;
479 if let Some(progress) = progress.as_ref() {
480 progress.notify_steps(WASM_TRAMPOLINE_ESTIMATED_BODY_SIZE)?;
481 }
482 Ok(trampoline)
483 })
484 .collect::<Result<Vec<FunctionBody>, CompileError>>()?
485 .into_iter()
486 .collect();
487 #[cfg(feature = "rayon")]
488 let function_call_trampolines = module
489 .signatures
490 .values()
491 .collect::<Vec<_>>()
492 .par_iter()
493 .map_init(FunctionBuilderContext::new, |cx, sig| {
494 let trampoline = make_trampoline_function_call(
495 &self.config().callbacks,
496 &*isa,
497 target.triple().architecture,
498 cx,
499 sig,
500 &module_hash,
501 )?;
502 if let Some(progress) = progress.as_ref() {
503 progress.notify_steps(WASM_TRAMPOLINE_ESTIMATED_BODY_SIZE)?;
504 }
505 Ok(trampoline)
506 })
507 .collect::<Result<Vec<FunctionBody>, CompileError>>()?
508 .into_iter()
509 .collect();
510
511 use wasmer_types::VMOffsets;
512 let offsets = VMOffsets::new_for_trampolines(frontend_config.pointer_bytes());
513 #[cfg(not(feature = "rayon"))]
515 let mut cx = FunctionBuilderContext::new();
516 #[cfg(not(feature = "rayon"))]
517 let dynamic_function_trampolines = module
518 .imported_function_types()
519 .collect::<Vec<_>>()
520 .into_iter()
521 .map(|func_type| {
522 let trampoline = make_trampoline_dynamic_function(
523 &self.config().callbacks,
524 &*isa,
525 target.triple().architecture,
526 &offsets,
527 &mut cx,
528 &func_type,
529 &module_hash,
530 )?;
531 if let Some(progress) = progress.as_ref() {
532 progress.notify_steps(WASM_TRAMPOLINE_ESTIMATED_BODY_SIZE)?;
533 }
534 Ok(trampoline)
535 })
536 .collect::<Result<Vec<_>, CompileError>>()?
537 .into_iter()
538 .collect();
539 #[cfg(feature = "rayon")]
540 let dynamic_function_trampolines = module
541 .imported_function_types()
542 .collect::<Vec<_>>()
543 .par_iter()
544 .map_init(FunctionBuilderContext::new, |cx, func_type| {
545 let trampoline = make_trampoline_dynamic_function(
546 &self.config().callbacks,
547 &*isa,
548 target.triple().architecture,
549 &offsets,
550 cx,
551 func_type,
552 &module_hash,
553 )?;
554 if let Some(progress) = progress.as_ref() {
555 progress.notify_steps(WASM_TRAMPOLINE_ESTIMATED_BODY_SIZE)?;
556 }
557 Ok(trampoline)
558 })
559 .collect::<Result<Vec<_>, CompileError>>()?
560 .into_iter()
561 .collect();
562
563 let got = wasmer_compiler::types::function::GOT::empty();
564
565 Ok(Compilation {
566 functions: functions.into_iter().collect(),
567 custom_sections,
568 function_call_trampolines,
569 dynamic_function_trampolines,
570 unwind_info,
571 got,
572 })
573 }
574}
575
576impl Compiler for CraneliftCompiler {
577 fn name(&self) -> &str {
578 "cranelift"
579 }
580
581 fn get_perfmap_enabled(&self) -> bool {
582 self.config.enable_perfmap
583 }
584
585 fn deterministic_id(&self) -> String {
586 String::from("cranelift")
587 }
588
589 fn get_middlewares(&self) -> &[Arc<dyn ModuleMiddleware>] {
591 &self.config.middlewares
592 }
593
594 fn compile_module(
597 &self,
598 target: &Target,
599 compile_info: &CompileModuleInfo,
600 module_translation_state: &ModuleTranslationState,
601 function_body_inputs: PrimaryMap<LocalFunctionIndex, FunctionBodyData<'_>>,
602 progress_callback: Option<&CompilationProgressCallback>,
603 ) -> Result<Compilation, CompileError> {
604 self.compile_module_internal(
605 target,
606 compile_info,
607 module_translation_state,
608 function_body_inputs,
609 progress_callback,
610 )
611 }
612}
613
614fn mach_reloc_to_reloc(
615 module: &ModuleInfo,
616 func_index_map: &cranelift_entity::PrimaryMap<ir::UserExternalNameRef, ir::UserExternalName>,
617 reloc: &FinalizedMachReloc,
618) -> Relocation {
619 let FinalizedMachReloc {
620 offset,
621 kind,
622 addend,
623 target,
624 } = &reloc;
625 let name = match target {
626 FinalizedRelocTarget::ExternalName(external_name) => external_name,
627 FinalizedRelocTarget::Func(_) => {
628 unimplemented!("relocations to offset in the same function are not yet supported")
629 }
630 };
631 let reloc_target: RelocationTarget = if let ExternalName::User(extname_ref) = name {
632 let func_index = func_index_map[*extname_ref].index;
633 RelocationTarget::LocalFunc(
635 module
636 .local_func_index(FunctionIndex::from_u32(func_index))
637 .expect("The provided function should be local"),
638 )
639 } else if let ExternalName::LibCall(libcall) = name {
640 RelocationTarget::LibCall(irlibcall_to_libcall(*libcall))
641 } else {
642 panic!("unrecognized external target")
643 };
644 Relocation {
645 kind: irreloc_to_relocationkind(*kind),
646 reloc_target,
647 offset: *offset,
648 addend: *addend,
649 }
650}
651
652fn mach_trap_to_trap(trap: &MachTrap) -> TrapInformation {
653 let &MachTrap { offset, code } = trap;
654 TrapInformation {
655 code_offset: offset,
656 trap_code: translate_ir_trapcode(code),
657 }
658}
659
660fn translate_ir_trapcode(trap: ir::TrapCode) -> TrapCode {
662 if trap == ir::TrapCode::STACK_OVERFLOW {
663 TrapCode::StackOverflow
664 } else if trap == ir::TrapCode::HEAP_OUT_OF_BOUNDS {
665 TrapCode::HeapAccessOutOfBounds
666 } else if trap == crate::TRAP_HEAP_MISALIGNED {
667 TrapCode::UnalignedAtomic
668 } else if trap == crate::TRAP_TABLE_OUT_OF_BOUNDS {
669 TrapCode::TableAccessOutOfBounds
670 } else if trap == crate::TRAP_INDIRECT_CALL_TO_NULL {
671 TrapCode::IndirectCallToNull
672 } else if trap == crate::TRAP_BAD_SIGNATURE {
673 TrapCode::BadSignature
674 } else if trap == ir::TrapCode::INTEGER_OVERFLOW {
675 TrapCode::IntegerOverflow
676 } else if trap == ir::TrapCode::INTEGER_DIVISION_BY_ZERO {
677 TrapCode::IntegerDivisionByZero
678 } else if trap == ir::TrapCode::BAD_CONVERSION_TO_INTEGER {
679 TrapCode::BadConversionToInteger
680 } else if trap == crate::TRAP_UNREACHABLE {
681 TrapCode::UnreachableCodeReached
682 } else if trap == crate::TRAP_INTERRUPT {
683 unimplemented!("Interrupts not supported")
684 } else if trap == crate::TRAP_NULL_REFERENCE || trap == crate::TRAP_NULL_I31_REF {
685 unimplemented!("Null reference not supported")
686 } else {
687 unimplemented!("Trap code {trap:?} not supported")
688 }
689}