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