Skip to main content

wasi_virt_layer_cli/generator/
special_func.rs

1use eyre::Context as _;
2use walrus::*;
3
4use crate::{
5    generator::{Generator, GeneratorCtx, ModuleExternal},
6    instrs::InstrRewrite as _,
7    unique_name::UniqueName,
8    util::{ResultUtil as _, WalrusFID, WalrusUtilFuncs as _, WalrusUtilModule as _, WasmName},
9};
10
11#[derive(Debug, strum::AsRefStr, strum::EnumCount, Hash, PartialEq, Eq)]
12#[strum(serialize_all = "snake_case")]
13pub enum SpecialFuncUniqueName<'a> {
14    Resetter(&'a WasmName),
15    ResetOnThread,
16    ResetOnThreadOnce,
17    StartInitOld,
18    Start(&'a WasmName),
19    MainVoid(&'a WasmName),
20    Reset(&'a WasmName),
21}
22
23/// To enable the reset function,
24/// a memory area shall be provided
25/// to retain memory information at startup.
26pub struct VFSExternalMemoryManager {
27    external_size: usize,
28    current_size: usize, // * 64KiB
29    mem_id: MemoryId,
30}
31
32impl VFSExternalMemoryManager {
33    pub fn new(module: &mut walrus::Module) -> Self {
34        let mem_id = module.memories.add_local(true, false, 0, None, None);
35
36        Self {
37            external_size: 0,
38            current_size: 0,
39            mem_id,
40        }
41    }
42
43    pub fn memory_id(&self) -> MemoryId {
44        self.mem_id
45    }
46
47    pub fn alloc(&mut self, size: usize) -> usize {
48        let ptr = self.current_size * 64 * 1024 + self.external_size;
49        self.external_size += size;
50
51        ptr
52    }
53
54    pub fn flush(mut self, module: &mut walrus::Module, threads: bool) -> eyre::Result<MemoryId> {
55        let external_size = (0..=0x10000)
56            .find(|i| *i * 64 * 1024 >= self.external_size)
57            .ok_or_else(|| eyre::eyre!("Failed to find external size in 0..=0x10000"))?;
58
59        self.current_size += external_size;
60
61        let mem = module.memories.get_mut(self.mem_id);
62
63        mem.initial = self.current_size as u64;
64        mem.shared = threads;
65
66        if threads {
67            mem.maximum = Some(mem.initial);
68        }
69
70        Ok(self.mem_id)
71    }
72}
73
74#[derive(Debug, Default)]
75pub struct ResetFunc;
76
77impl Generator for ResetFunc {
78    fn post_combine(
79        &mut self,
80        module: &mut walrus::Module,
81        ctx: &GeneratorCtx,
82    ) -> eyre::Result<()> {
83        let mut mem_manager = VFSExternalMemoryManager::new(module);
84
85        let wasm_mem = ctx.vfs_used_memory_id.unwrap();
86
87        let initializers = module
88            .add_func(&[], &[], |_, _| Ok(()))
89            .wrap_err_with(|| eyre::eyre!("Failed to add initializer function"))?;
90
91        let tmp_start_section_id = module.add_func(&[], &[], |_, _| Ok(()))?;
92
93        for wasm in &ctx.target_names {
94            if let Some(reset) = (
95                UniqueName::NAMESPACE,
96                &UniqueName::SpecialFunc(&SpecialFuncUniqueName::Reset(wasm)),
97            )
98                .get_fid(&module.imports)
99                .ok()
100            {
101                let global = ctx.target_used_global_id.as_ref().unwrap()[wasm]
102                    .iter()
103                    .copied()
104                    .map(|g| module.globals.get(g))
105                    .filter(|g| g.mutable)
106                    .filter_map(|g| {
107                        if let GlobalKind::Local(ConstExpr::Value(v)) = g.kind {
108                            Some((g.id(), v.clone()))
109                        } else {
110                            log::warn!(
111                            "Global segment {:?} is not a value, we support only local variables",
112                            g.kind
113                        );
114                            None
115                        }
116                    })
117                    .collect::<Box<_>>();
118
119                let data_range = module
120                    .data
121                    .iter()
122                    .filter_map(|data| {
123                        match &data.kind {
124                            DataKind::Active { memory, offset } if *memory == wasm_mem => {
125                                if let ConstExpr::Value(v) = offset {
126                                    if let ir::Value::I32(offset) = v {
127                                        Some((*offset, data.value.len()))
128                                    } else {
129                                        log::warn!(
130                                            "Data segment {:?} is not i32, we support only i32",
131                                            offset
132                                        );
133                                        None
134                                    }
135                                } else {
136                                    log::warn!(
137                                        "Data segment {:?} is not a value, we support only i32",
138                                        offset
139                                    );
140                                    None
141                                }
142                            }
143                            // Passive is across memories so ignore on now
144                            _ => None,
145                        }
146                    })
147                    .collect::<Box<_>>();
148
149                let zero_range = std::iter::once(Some(0i32))
150                    .chain(
151                        data_range
152                            .iter()
153                            .flat_map(|(offset, len)| [Some(*offset), Some(*offset + *len as i32)]),
154                    )
155                    .chain(std::iter::once(None))
156                    .collect::<Vec<_>>()
157                    .chunks(2)
158                    .map(|chunk| (chunk[0].unwrap(), chunk[1]))
159                    .collect::<Box<_>>();
160
161                let mem_init = data_range
162                    .into_iter()
163                    .map(|(offset, len)| (offset, len, mem_manager.alloc(len)))
164                    .collect::<Box<_>>();
165
166                let reset_area_mem_id = mem_manager.memory_id();
167
168                let resetter = module
169                    .replace_imported_func(reset, |(builder, _)| {
170                        let mut body = builder.func_body();
171
172                        for (id, value) in global.iter() {
173                            body.const_(*value).global_set(*id);
174                        }
175                        for (start, end) in zero_range.iter() {
176                            // ptr
177                            body.i32_const(*start)
178                                // value
179                                .i32_const(0);
180
181                            // len
182                            if let Some(end) = end {
183                                body.i32_const(*end - *start);
184                            } else {
185                                body.memory_size(wasm_mem);
186
187                                // asserter.as_mut().unwrap()(&mut body).unwrap();
188
189                                body.i32_const(64 * 1024)
190                                    .binop(ir::BinaryOp::I32Mul)
191                                    .i32_const(*start)
192                                    .binop(ir::BinaryOp::I32Sub);
193                            }
194                            body.memory_fill(wasm_mem);
195                        }
196                        for (mem_offset, mem_len, mem_ptr) in mem_init.iter() {
197                            body.i32_const(*mem_offset) // dst
198                                .i32_const(*mem_ptr as i32) // src
199                                .i32_const(*mem_len as i32) // len
200                                .memory_copy(reset_area_mem_id, wasm_mem);
201                        }
202
203                        body.call(tmp_start_section_id);
204                    })
205                    .to_eyre()
206                    .wrap_err_with(|| eyre::eyre!("Failed to replace reset function for {wasm}"))?;
207
208                if ctx.unstable_print_debug {
209                    module.exports.add(
210                        &UniqueName::SpecialFunc(&SpecialFuncUniqueName::Resetter(wasm))
211                            .to_string(),
212                        resetter,
213                    );
214                }
215
216                let mut func_body = module
217                    .funcs
218                    .get_mut(initializers)
219                    .kind
220                    .unwrap_local_mut()
221                    .builder_mut()
222                    .func_body();
223
224                for (offset, len, ptr) in mem_init {
225                    func_body
226                        .i32_const(ptr as i32) // dst
227                        .i32_const(offset) // src
228                        .i32_const(len as i32) // len
229                        .memory_copy(wasm_mem, reset_area_mem_id);
230                }
231            }
232        }
233
234        let _ = mem_manager.flush(module, ctx.threads)?;
235
236        // Saves the memory state upon initial startup.
237        // As the start section is also invoked when spawning threads,
238        // ensure it is called only once if threads are enabled.
239        let init_id = if ctx.threads {
240            let reset_on_thread = UniqueName::SpecialFunc(&SpecialFuncUniqueName::ResetOnThread)
241                .get_fid(&module.exports)?;
242            let reset_on_thread_once = (
243                UniqueName::NAMESPACE,
244                &UniqueName::SpecialFunc(&SpecialFuncUniqueName::ResetOnThreadOnce),
245            )
246                .get_fid(&module.imports)?;
247
248            // module.imports.erase(reset_on_thread_once)?;
249
250            // module.exports.erase(reset_on_thread)?;
251            // module.funcs.delete(reset_on_thread);
252
253            module.renew_call_fn(reset_on_thread_once, initializers)?;
254
255            reset_on_thread
256        } else {
257            initializers
258        };
259
260        let old_start = module.start.clone();
261        let new_start = module
262            .add_func(&[], &[], |builder, _| {
263                let mut body = builder.func_body();
264                body.call(init_id); // save environment
265                if let Some(old_start) = old_start {
266                    body.call(old_start);
267                }
268                Ok(())
269            })
270            .wrap_err_with(|| eyre::eyre!("Failed to add new start function"))?;
271
272        module.start = Some(new_start);
273
274        module.renew_call_fn(tmp_start_section_id, new_start)?;
275
276        if let Some(start) = old_start {
277            if ctx.unstable_print_debug {
278                module.exports.add(
279                    &UniqueName::SpecialFunc(&SpecialFuncUniqueName::StartInitOld).to_string(),
280                    start,
281                );
282            }
283        }
284
285        // memory_init(memory, data)
286        // fn(&mut self, Id<Memory>, Id<Data>)
287        // data_drop(&mut self, data: DataId)
288        // so we remove all data_drop sections.
289        // Prevent the active segment from being deleted
290        // so that it can be called upon as many times as required.
291        module
292            .funcs
293            .iter_mut()
294            .map(|func| {
295                match &mut func.kind {
296                    walrus::FunctionKind::Local(l) => {
297                        l.builder_mut()
298                            .func_body()
299                            .retain(|instr, _| !instr.is_data_drop());
300                    }
301                    _ => {}
302                }
303                Ok(())
304            })
305            .collect::<eyre::Result<Vec<_>>>()?;
306
307        Ok(())
308    }
309}
310
311#[derive(Debug, Default)]
312pub struct StartFunc;
313
314impl Generator for StartFunc {
315    fn pre_target(
316        &mut self,
317        module: &mut walrus::Module,
318        _: &GeneratorCtx,
319        external: &ModuleExternal,
320    ) -> eyre::Result<()> {
321        let id = "_start".get_fid(&module.exports)?;
322
323        module
324            .exports
325            .get_mut(module.exports.get_exported_func(id).unwrap().id())
326            .name =
327            UniqueName::SpecialFunc(&SpecialFuncUniqueName::Start(&external.name)).to_string();
328
329        Ok(())
330    }
331
332    fn post_combine(
333        &mut self,
334        module: &mut walrus::Module,
335        ctx: &GeneratorCtx,
336    ) -> eyre::Result<()> {
337        for wasm in &ctx.target_names {
338            module.renew_call_fn(
339                (
340                    UniqueName::NAMESPACE,
341                    &UniqueName::SpecialFunc(&SpecialFuncUniqueName::Start(wasm)),
342                )
343                    .get_fid(&module.imports)?,
344                ctx.start_func_id.as_ref().unwrap()[wasm],
345                // Export already removed by StartFuncIdVisitor
346            )?;
347        }
348
349        Ok(())
350    }
351}
352
353#[derive(Debug, Default)]
354pub struct MainVoidFunc;
355
356impl Generator for MainVoidFunc {
357    fn pre_target(
358        &mut self,
359        module: &mut walrus::Module,
360        _: &GeneratorCtx,
361        external: &ModuleExternal,
362    ) -> eyre::Result<()> {
363        let id = "__main_void".get_fid(&module.exports)?;
364
365        module
366            .exports
367            .get_mut(module.exports.get_exported_func(id).unwrap().id())
368            .name =
369            UniqueName::SpecialFunc(&SpecialFuncUniqueName::MainVoid(&external.name)).to_string();
370
371        Ok(())
372    }
373
374    fn post_combine(
375        &mut self,
376        module: &mut walrus::Module,
377        ctx: &GeneratorCtx,
378    ) -> eyre::Result<()> {
379        for wasm in &ctx.target_names {
380            if let Some(fid) = (
381                UniqueName::NAMESPACE,
382                &UniqueName::SpecialFunc(&SpecialFuncUniqueName::MainVoid(wasm)),
383            )
384                .get_fid(&module.imports)
385                .ok()
386            {
387                let main_void_func_name =
388                    UniqueName::SpecialFunc(&SpecialFuncUniqueName::MainVoid(wasm)).to_string();
389                let main_void_func_id = main_void_func_name.get_fid(&module.exports)?;
390                let start_fn_id = ctx.start_func_id.as_ref().unwrap()[wasm];
391
392                let fake_fn_id = module.add_func(&[], &[walrus::ValType::I32], |func, _| {
393                    func.func_body().i32_const(0).return_();
394
395                    Ok(())
396                })?;
397
398                let call_main_void: i32 = module
399                    .funcs
400                    .rewrite(
401                        |instr, _| {
402                            if let walrus::ir::Instr::Call(c) = instr {
403                                if c.func == main_void_func_id {
404                                    c.func = fake_fn_id;
405                                    1
406                                } else {
407                                    0
408                                }
409                            } else {
410                                0
411                            }
412                        },
413                        start_fn_id,
414                    )
415                    .wrap_err("Failed to read main_void calls")?
416                    .into_iter()
417                    .sum();
418
419                if call_main_void == 0 {
420                    let call_count = module
421                        .funcs
422                        .flat_read(
423                            |instr, _| {
424                                if let walrus::ir::Instr::Call(c) = instr {
425                                    if c.func == main_void_func_id { 1 } else { 0 }
426                                } else {
427                                    0
428                                }
429                            },
430                            start_fn_id,
431                        )
432                        .wrap_err("Failed to read main_void calls")?
433                        .into_iter()
434                        .count();
435
436                    if call_count == 1 {
437                        log::warn!(
438                            "main_void is not called directly in start function, but called in nested function. we replaced once call to a fake function that returns 0."
439                        );
440                    } else {
441                        if call_count > 1 {
442                            log::warn!(
443                                "main_void is not called directly in start function, and called in nested function. main_void called multiple times in start function, rust's default is once."
444                            );
445                        } else {
446                            log::warn!(
447                                "main_void is not called in nested start function, we think call_indirect is used. we replaced all calls to a fake function that returns 0."
448                            );
449                            // Strictly speaking, it should be limited to functions called within start_fn,
450                            // but since the main_void function is only called inside start_fn and through export,
451                            // it is acceptable to modify it in this function.
452                            module
453                                .renew_call_fn(main_void_func_id, fake_fn_id)
454                                .wrap_err("Failed to rewrite main_void call in start")?;
455                        }
456                    }
457                    let start_fn_id =
458                        module.nested_copy_func(start_fn_id, &[start_fn_id], true, true)?;
459                    module
460                        .funcs
461                        .flat_rewrite(
462                            |instr, _| {
463                                if let walrus::ir::Instr::Call(c) = instr {
464                                    if c.func == main_void_func_id {
465                                        c.func = fake_fn_id;
466                                    }
467                                }
468                            },
469                            start_fn_id,
470                            false,
471                        )
472                        .wrap_err("Failed to read main_void calls")?;
473                } else if call_main_void > 1 {
474                    log::warn!(
475                        "main_void called multiple times in start function, rust's default is once. we replaced all calls to a fake function that returns 0."
476                    );
477                }
478
479                module.connect_func_alt_with_remove_export(
480                    fid,
481                    main_void_func_name,
482                    ctx.unstable_print_debug,
483                )?;
484            } else {
485                log::warn!(
486                    "No main_void found for {wasm}. You can use {} directly",
487                    UniqueName::SpecialFunc(&SpecialFuncUniqueName::MainVoid(wasm)).to_string()
488                );
489            }
490        }
491
492        Ok(())
493    }
494}