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