Skip to main content

wasi_virt_layer_cli/generator/
special_func.rs

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