Skip to main content

wasi_virt_layer_cli/wasm_stream/
pipeline.rs

1use eyre::Context as _;
2
3pub trait StreamPass: Send + Sync {
4    /// Runs the transformation pass on the provided WebAssembly binary.
5    /// Returns the modified WebAssembly binary.
6    fn run(&mut self, input_wasm: &[u8]) -> eyre::Result<Vec<u8>>;
7}
8
9pub trait StreamChecker: Send + Sync {
10    fn check(&mut self, payload: &wasmparser::Payload) -> eyre::Result<()>;
11}
12
13pub struct ParallelCheckStreamPass {
14    checkers: Vec<Box<dyn StreamChecker>>,
15}
16
17impl ParallelCheckStreamPass {
18    pub fn new(checkers: Vec<Box<dyn StreamChecker>>) -> Self {
19        Self { checkers }
20    }
21}
22
23impl StreamPass for ParallelCheckStreamPass {
24    fn run(&mut self, input_wasm: &[u8]) -> eyre::Result<Vec<u8>> {
25        for payload in wasmparser::Parser::new(0).parse_all(input_wasm) {
26            let payload = payload?;
27            // Process checkers sequentially for now (parsing itself is fast,
28            // and parallelizing across lightweight checkers might not outweigh thread overhead,
29            // but the architecture allows replacing this loop with rayon later).
30            for checker in &mut self.checkers {
31                checker.check(&payload)?;
32            }
33        }
34        Ok(input_wasm.to_vec())
35    }
36}
37
38/// A pipeline of sequential WebAssembly transformations.
39pub struct Pipeline {
40    passes: Vec<Box<dyn StreamPass>>,
41}
42
43/// Helper function to process all functions in a CodeSection in parallel.
44/// Takes the raw bytes of the CodeSection, and a transformation function.
45pub fn par_process_code_section<F>(
46    code_section: wasmparser::CodeSectionReader<'_>,
47    transform: F,
48) -> eyre::Result<wasm_encoder::CodeSection>
49where
50    F: Fn(usize, wasmparser::FunctionBody<'_>) -> eyre::Result<wasm_encoder::Function>
51        + Sync
52        + Send,
53{
54    use eyre::Context;
55    use rayon::prelude::*;
56
57    // Collect all function bodies
58    let bodies = code_section
59        .into_iter()
60        .collect::<Result<Vec<_>, _>>()
61        .wrap_err("Failed to read function bodies")?;
62
63    // Process them in parallel
64    let encoded_functions = bodies
65        .into_par_iter()
66        .enumerate()
67        .map(|(i, body)| transform(i, body))
68        .collect::<eyre::Result<Vec<_>>>()?;
69
70    // Stitch back together
71    let mut new_code_section = wasm_encoder::CodeSection::new();
72    for encoded_func in encoded_functions {
73        new_code_section.function(&encoded_func);
74    }
75
76    Ok(new_code_section)
77}
78
79impl Pipeline {
80    /// Create a new empty streaming pipeline.
81    pub fn new() -> Self {
82        Self { passes: Vec::new() }
83    }
84
85    /// Add a streaming pass to the pipeline.
86    pub fn add_pass(&mut self, pass: Box<dyn StreamPass>) {
87        self.passes.push(pass);
88    }
89
90    /// Run all passes in the pipeline sequentially on the given WebAssembly module.
91    pub fn run(&mut self, input_wasm: &[u8]) -> eyre::Result<Vec<u8>> {
92        let mut current_wasm = input_wasm.to_vec();
93        log::debug!("PIPELINE RUN IS EXECUTING!");
94
95        let mut i = 0;
96        for pass in &mut self.passes {
97            log::debug!("RUNNING STREAM PASS #{}", i);
98            current_wasm = pass
99                .run(&current_wasm)
100                .wrap_err_with(|| format!("Failed in stream pass #{i}"))?;
101            i += 1;
102        }
103
104        Ok(current_wasm)
105    }
106}