1 use anyhow::{Context as _, Result};
2 use std::fs::File;
3 use std::io::Write;
4 use std::path::Path;
5 use target_lexicon::Triple;
6 use wasmtime::{CodeBuilder, Config, Engine};
7 
8 pub fn compile_cranelift(
9     wasm: &[u8],
10     path: Option<&Path>,
11     target: Option<Triple>,
12     output: impl AsRef<Path>,
13 ) -> Result<()> {
14     let mut config = Config::new();
15     config.debug_info(true);
16     if let Some(target) = target {
17         config.target(&target.to_string())?;
18     }
19     let engine = Engine::new(&config)?;
20     let module = CodeBuilder::new(&engine)
21         .wasm_binary_or_text(wasm, path)?
22         .compile_module()?;
23     let bytes = module.serialize()?;
24 
25     let mut file = File::create(output).context("failed to create object file")?;
26     file.write_all(&bytes)
27         .context("failed to write object file")?;
28 
29     Ok(())
30 }
31