Skip to main content

wasi_virt_layer_cli/generator/
wrap_unreachable.rs

1use std::collections::HashSet;
2
3use walrus::{ConstExpr, ExportItem, FunctionId, Module, ValType, ir::*};
4
5use crate::{
6    generator::{Generator, GeneratorCtx, ModuleExternal},
7    instrs::InstrRewrite as _,
8    util::{WalrusFID, WalrusUtilExport, WalrusUtilModule, WasmName},
9};
10
11// ── Naming ────────────────────────────────────────────────────────────
12
13/// Import module used by the `wrap_unreachable!` macro on the library side.
14///
15/// This is ABI-locked in `wasi_virt_layer::wasi::wrap_unreachable` and must
16/// stay in sync with the library macro.
17const WRAP_UNREACHABLE_MODULE: &str = "__wasip1_virt_layer";
18
19/// Structured names associated with the wrap-unreachable feature for a
20/// specific target module.
21///
22/// Follows the same pattern as [`SpecialFuncUniqueName`] and other
23/// per-generator name enums, but uses the `__wasip1_virt_layer_` prefix
24/// because these names are ABI-locked with the library-side macro.
25///
26/// [`SpecialFuncUniqueName`]: crate::generator::special_func::SpecialFuncUniqueName
27#[derive(Debug, strum::AsRefStr, strum::EnumCount, Hash, PartialEq, Eq)]
28#[strum(serialize_all = "snake_case")]
29pub enum WrapUnreachableName<'a> {
30    /// Marker export that opts a target into unreachable wrapping.
31    WrapUnreachable(&'a WasmName),
32    /// Getter for the per-target `unreachable_flag` global.
33    GetUnreachableFlag(&'a WasmName),
34    /// Setter for the per-target `unreachable_flag` global.
35    SetUnreachableFlag(&'a WasmName),
36    /// VFS handler: maps the flag value to a proper exit code.
37    FixMainRawExitCode(&'a WasmName),
38    /// VFS handler: propagates thread exit when the flag is set.
39    HandleThreadExit(&'a WasmName),
40}
41
42impl WrapUnreachableName<'_> {
43    /// The prefix used for all wrap-unreachable names, matching the library macro.
44    const PREFIX: &'static str = "__wasip1_virt_layer_";
45
46    /// Formats this name into the full ABI-locked string.
47    fn to_name(&self) -> String {
48        let variant = self.as_ref();
49        match self {
50            Self::WrapUnreachable(wasm)
51            | Self::GetUnreachableFlag(wasm)
52            | Self::SetUnreachableFlag(wasm)
53            | Self::FixMainRawExitCode(wasm)
54            | Self::HandleThreadExit(wasm) => {
55                format!("{}{wasm}_{variant}", Self::PREFIX)
56            }
57        }
58    }
59}
60
61impl std::fmt::Display for WrapUnreachableName<'_> {
62    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
63        f.write_str(&self.to_name())
64    }
65}
66
67// ── Dummy-value helpers ───────────────────────────────────────────────
68
69/// Returns a zero-valued [`Value`] matching the given Wasm value type.
70///
71/// # Panics
72///
73/// Panics on `ValType::Ref`, which is not supported.
74fn dummy_value(ty: &ValType) -> Value {
75    match ty {
76        ValType::I32 => Value::I32(0),
77        ValType::I64 => Value::I64(0),
78        ValType::F32 => Value::F32(0.0),
79        ValType::F64 => Value::F64(0.0),
80        ValType::V128 => Value::V128(0),
81        ValType::Ref(_) => unimplemented!("Ref types not supported for dummy returns"),
82    }
83}
84
85/// Appends dummy-constant instructions for every return type followed by a
86/// `return` instruction.
87fn push_dummy_return(
88    instrs: &mut Vec<(Instr, InstrLocId)>,
89    return_types: &[ValType],
90    loc: InstrLocId,
91) {
92    for ty in return_types {
93        instrs.push((
94            Instr::Const(Const {
95                value: dummy_value(ty),
96            }),
97            loc,
98        ));
99    }
100    instrs.push((Instr::Return(Return {}), loc));
101}
102
103// ── Instruction scanning ──────────────────────────────────────────────
104
105/// Positions of interesting instructions found during a recursive scan.
106struct InstrScanResult {
107    /// `(seq_id, index)` pairs for `Unreachable` instructions.
108    unreachables: Vec<(InstrSeqId, usize)>,
109    /// `(seq_id, index)` pairs for `Call` / `CallIndirect` instructions.
110    calls: Vec<(InstrSeqId, usize)>,
111}
112
113/// Walks every instruction sequence within `func`, recording
114/// positions of `unreachable` and `call` / `call_indirect` instructions.
115fn scan_instructions(func: &walrus::LocalFunction) -> InstrScanResult {
116    let mut result = InstrScanResult {
117        unreachables: Vec::new(),
118        calls: Vec::new(),
119    };
120
121    let mut visited = HashSet::new();
122    let mut work_stack = vec![func.entry_block()];
123
124    while let Some(seq_id) = work_stack.pop() {
125        if visited.contains(&seq_id) {
126            continue;
127        }
128        visited.insert(seq_id);
129
130        for (i, (instr, _)) in func.block(seq_id).instrs.iter().enumerate() {
131            match instr {
132                Instr::Unreachable(_) => result.unreachables.push((seq_id, i)),
133                Instr::Call(_) | Instr::CallIndirect(_) => result.calls.push((seq_id, i)),
134                Instr::Block(b) => {
135                    if !visited.contains(&b.seq) {
136                        work_stack.push(b.seq);
137                    }
138                }
139                Instr::Loop(l) => {
140                    if !visited.contains(&l.seq) {
141                        work_stack.push(l.seq);
142                    }
143                }
144                Instr::IfElse(ie) => {
145                    if !visited.contains(&ie.consequent) {
146                        work_stack.push(ie.consequent);
147                    }
148                    if !visited.contains(&ie.alternative) {
149                        work_stack.push(ie.alternative);
150                    }
151                }
152                _ => {}
153            }
154        }
155    }
156
157    result
158}
159
160// ── Instruction patching ──────────────────────────────────────────────
161
162/// Replaces every `unreachable` instruction at the recorded positions with
163/// a *set-flag + dummy-return* sequence.
164///
165/// Processes sites in reverse index order so that earlier indices remain valid.
166fn patch_unreachables(
167    func: &mut walrus::LocalFunction,
168    sites: &mut [(InstrSeqId, usize)],
169    flag_global: walrus::GlobalId,
170    return_types: &[ValType],
171) {
172    sites.sort_unstable_by(|a, b| b.cmp(a));
173
174    for &(seq_id, idx) in sites.iter() {
175        let seq = func.block_mut(seq_id);
176        let (_removed, loc) = seq.instrs.remove(idx);
177
178        let mut new_instrs = Vec::with_capacity(return_types.len() + 3);
179        new_instrs.push((
180            Instr::Const(Const {
181                value: Value::I32(1),
182            }),
183            loc,
184        ));
185        new_instrs.push((
186            Instr::GlobalSet(GlobalSet {
187                global: flag_global,
188            }),
189            loc,
190        ));
191        push_dummy_return(&mut new_instrs, return_types, loc);
192
193        for (j, instr) in new_instrs.into_iter().enumerate() {
194            seq.instrs.insert(idx + j, instr);
195        }
196    }
197}
198
199/// Inserts a post-call flag-check after every `call` / `call_indirect` at the
200/// recorded positions.
201///
202/// The check is: `if (flag) { push dummy values; return; } else { /* nop */ }`.
203/// Processes sites in reverse index order.
204fn hook_calls(
205    func: &mut walrus::LocalFunction,
206    sites: &mut [(InstrSeqId, usize)],
207    flag_global: walrus::GlobalId,
208    return_types: &[ValType],
209) {
210    sites.sort_unstable_by(|a, b| b.cmp(a));
211
212    for &(seq_id, idx) in sites.iter() {
213        let insert_idx = idx + 1;
214
215        // Read the source location from the call instruction (NLL drops this borrow).
216        let loc = func.block(seq_id).instrs[idx].1;
217
218        // Build the consequent (flag-is-set) branch: dummy return.
219        let consequent_seq = func.builder_mut().dangling_instr_seq(None).id();
220        {
221            let consequent = func.block_mut(consequent_seq);
222            push_dummy_return(&mut consequent.instrs, return_types, loc);
223        }
224
225        // Empty alternative (flag-is-clear) branch.
226        let alternative_seq = func.builder_mut().dangling_instr_seq(None).id();
227
228        // Insert the check after the call.
229        let seq = func.block_mut(seq_id);
230        let check = [
231            (
232                Instr::GlobalGet(GlobalGet {
233                    global: flag_global,
234                }),
235                loc,
236            ),
237            (
238                Instr::IfElse(IfElse {
239                    consequent: consequent_seq,
240                    alternative: alternative_seq,
241                }),
242                loc,
243            ),
244        ];
245
246        for (j, instr) in check.into_iter().enumerate() {
247            seq.instrs.insert(insert_idx + j, instr);
248        }
249    }
250}
251
252// ── Export wrapping ───────────────────────────────────────────────────
253
254/// Wraps the `__main_void` export so that, after calling the original
255/// function, the unreachable flag is checked and forwarded to
256/// `fix_main_raw_exit_code` when set.
257fn wrap_main_void(
258    module: &mut Module,
259    flag_global: walrus::GlobalId,
260    fix_exit_code_import: FunctionId,
261) -> eyre::Result<()> {
262    let Some((export_id, orig_func)) = find_export_func(module, "__main_void") else {
263        return Ok(());
264    };
265
266    let ret_local = module.locals.add(ValType::I32);
267    let wrapper = module.add_func(&[], &[ValType::I32], |builder, _| {
268        let mut body = builder.func_body();
269        body.call(orig_func);
270        body.local_set(ret_local);
271        body.global_get(flag_global);
272        body.if_else(
273            ValType::I32,
274            |then| {
275                then.global_get(flag_global);
276                then.call(fix_exit_code_import);
277            },
278            |else_| {
279                else_.local_get(ret_local);
280            },
281        );
282        Ok(())
283    })?;
284
285    module.exports.delete(export_id);
286    module.exports.add("__main_void", wrapper);
287    redirect_callers(module, orig_func, wrapper)?;
288
289    Ok(())
290}
291
292/// Wraps the `wasi_thread_start` export so that `handle_thread_exit` is
293/// invoked when the unreachable flag is set after the original entry point
294/// returns.
295fn wrap_thread_start(
296    module: &mut Module,
297    flag_global: walrus::GlobalId,
298    handle_thread_exit_import: FunctionId,
299) -> eyre::Result<()> {
300    let Some((export_id, orig_func)) = find_export_func(module, "wasi_thread_start") else {
301        return Ok(());
302    };
303
304    let wrapper = module.add_func(&[ValType::I32, ValType::I32], &[], |builder, args| {
305        let mut body = builder.func_body();
306        body.local_get(args[0]);
307        body.local_get(args[1]);
308        body.call(orig_func);
309        body.global_get(flag_global);
310        body.if_else(
311            None,
312            |then| {
313                then.global_get(flag_global);
314                then.call(handle_thread_exit_import);
315            },
316            |_| {},
317        );
318        Ok(())
319    })?;
320
321    module.exports.delete(export_id);
322    module.exports.add("wasi_thread_start", wrapper);
323    redirect_callers(module, orig_func, wrapper)?;
324
325    Ok(())
326}
327
328// ── Shared utilities ──────────────────────────────────────────────────
329
330/// Finds a function export by name, returning its export ID and function ID.
331fn find_export_func(module: &Module, name: &str) -> Option<(walrus::ExportId, FunctionId)> {
332    module
333        .exports
334        .iter()
335        .find(|e| e.name == name)
336        .and_then(|e| match e.item {
337            ExportItem::Function(f) => Some((e.id(), f)),
338            _ => None,
339        })
340}
341
342/// Redirects all callers of `old_func` to `new_func`, **excluding** calls
343/// inside `new_func` itself (to prevent infinite recursion in wrappers).
344fn redirect_callers(
345    module: &mut Module,
346    old_func: FunctionId,
347    new_func: FunctionId,
348) -> eyre::Result<()> {
349    let all_fids: Vec<FunctionId> = module.funcs.iter_local().map(|(id, _)| id).collect();
350
351    for fid in all_fids {
352        if fid == new_func {
353            continue;
354        }
355        let local = module.funcs.get_mut(fid).kind.unwrap_local_mut();
356        local.builder_mut().func_body().rewrite(|instr, _| {
357            if let Instr::Call(call) = instr {
358                if call.func == old_func {
359                    call.func = new_func;
360                }
361            }
362        })?;
363    }
364
365    Ok(())
366}
367
368/// Wires an import to its matching export (by name) and removes the export.
369///
370/// Silently skipped when either the import or the export is absent — not every
371/// target exports every helper.
372///
373/// The export is deleted by **name** rather than by function ID because, when
374/// multiple targets share the same underlying VFS handler function, the same
375/// `FunctionId` can appear in several exports simultaneously, which would
376/// cause a function-ID-based deletion to fail with "expected exactly one".
377fn wire_import_to_export(module: &mut Module, name: &str, debug: bool) -> eyre::Result<()> {
378    let Ok(import_fid) = (WRAP_UNREACHABLE_MODULE, name).get_fid(&module.imports) else {
379        return Ok(());
380    };
381    let Ok(export_fid) = name.get_fid(&module.exports) else {
382        return Ok(());
383    };
384
385    module.renew_call_fn(import_fid, export_fid)?;
386
387    // Delete by name: find the export whose name matches and remove it.
388    // We cannot use `erase_with(export_fid)` here because that helper
389    // searches by FunctionId and requires exactly one match — but after
390    // merging multiple targets the same function may be exported under
391    // several per-target names.
392    if !debug {
393        let export_id = module
394            .exports
395            .iter()
396            .find(|e| e.name == name)
397            .map(|e| e.id());
398        if let Some(export_id) = export_id {
399            module.exports.delete(export_id);
400        }
401    }
402
403    Ok(())
404}
405
406// ── Generator implementation ──────────────────────────────────────────
407
408/// Generator that replaces WebAssembly `unreachable` instructions and handles
409/// unwinding call stacks gracefully by injecting a global flag and modifying
410/// call sites.
411///
412/// When a VFS target module opts-in by exporting a
413/// `__wasip1_virt_layer_{target}_wrap_unreachable` marker (generated by the
414/// [`wrap_unreachable!`] macro), this generator:
415///
416/// 1. Adds a per-target global `unreachable_flag` to the target module.
417/// 2. Replaces every `unreachable` instruction with a flag-set + dummy-return
418///    sequence.
419/// 3. Hooks every `call` / `call_indirect` site with a post-call flag check
420///    that short-circuits with a dummy return when the flag is set.
421/// 4. Wraps `__main_void` and `wasi_thread_start` exports so the flag is
422///    forwarded to the VFS for proper exit-code / thread-exit handling.
423///
424/// [`wrap_unreachable!`]: wasi_virt_layer::wrap_unreachable
425#[derive(Debug, Default)]
426pub struct WrapUnreachableGenerator {
427    /// Target module names that opted in via the marker export.
428    targets: HashSet<String>,
429}
430
431impl Generator for WrapUnreachableGenerator {
432    fn pre_vfs(&mut self, module: &mut Module, ctx: &GeneratorCtx) -> eyre::Result<()> {
433        for target in ctx.target_names.iter() {
434            let marker = WrapUnreachableName::WrapUnreachable(&target).to_string();
435            if module.exports.iter().any(|e| e.name == marker) {
436                self.targets.insert(target.to_string());
437            }
438        }
439        Ok(())
440    }
441
442    fn post_combine(&mut self, module: &mut Module, ctx: &GeneratorCtx) -> eyre::Result<()> {
443        for target in &self.targets {
444            // Wire each helper import → export.
445            let helpers = helper_names_for(target, &ctx.target_names);
446            for name in &helpers {
447                wire_import_to_export(module, name, ctx.unstable_print_debug)?;
448            }
449
450            // Remove the opt-in marker export by name (not by function ID),
451            // for the same reason as in `wire_import_to_export`.
452            let marker = marker_name_for(target, &ctx.target_names);
453            if !ctx.unstable_print_debug {
454                let marker_eid = module
455                    .exports
456                    .iter()
457                    .find(|e| e.name == marker)
458                    .map(|e| e.id());
459                if let Some(eid) = marker_eid {
460                    module.exports.delete(eid);
461                }
462            }
463        }
464        Ok(())
465    }
466
467    fn pre_target(
468        &mut self,
469        module: &mut Module,
470        _: &GeneratorCtx,
471        external: &ModuleExternal,
472    ) -> eyre::Result<()> {
473        if !self.targets.contains(&external.name.to_string()) {
474            return Ok(());
475        }
476
477        let get_flag_name = WrapUnreachableName::GetUnreachableFlag(&external.name).to_string();
478        let set_flag_name = WrapUnreachableName::SetUnreachableFlag(&external.name).to_string();
479        let fix_exit_code_name =
480            WrapUnreachableName::FixMainRawExitCode(&external.name).to_string();
481        let handle_exit_name = WrapUnreachableName::HandleThreadExit(&external.name).to_string();
482
483        // ── 1. Per-target unreachable flag global ─────────────────────
484        let flag_global =
485            module
486                .globals
487                .add_local(ValType::I32, true, false, ConstExpr::Value(Value::I32(0)));
488
489        // ── 2. Export getter / setter for the flag ────────────────────
490        let getter = module.add_func(&[], &[ValType::I32], |builder, _| {
491            builder.func_body().global_get(flag_global);
492            Ok(())
493        })?;
494        module.exports.add(&get_flag_name, getter);
495
496        let setter = module.add_func(&[ValType::I32], &[], |builder, args| {
497            builder
498                .func_body()
499                .local_get(args[0])
500                .global_set(flag_global);
501            Ok(())
502        })?;
503        module.exports.add(&set_flag_name, setter);
504
505        // ── 3. Import VFS handler functions ───────────────────────────
506        let fix_exit_code_ty = module.types.add(&[ValType::I32], &[ValType::I32]);
507        let fix_exit_code_import = module
508            .add_import_func(
509                WRAP_UNREACHABLE_MODULE,
510                &fix_exit_code_name,
511                fix_exit_code_ty,
512            )
513            .0;
514
515        let handle_exit_ty = module.types.add(&[ValType::I32], &[]);
516        let handle_thread_exit_import = module
517            .add_import_func(WRAP_UNREACHABLE_MODULE, &handle_exit_name, handle_exit_ty)
518            .0;
519
520        // ── 4. Patch existing function instructions ───────────────────
521        // IMPORTANT: Must happen BEFORE creating wrapper functions below,
522        // so that the wrappers themselves are not processed by the
523        // call-hook loop. If the wrappers were processed, the hook after
524        // `call(orig_func)` would short-circuit with a dummy return,
525        // bypassing the fix_exit_code logic.
526        let func_ids: Vec<FunctionId> = module.funcs.iter_local().map(|(id, _)| id).collect();
527
528        for fid in func_ids {
529            let return_types = module
530                .types
531                .get(module.funcs.get(fid).ty())
532                .results()
533                .to_vec();
534
535            let mut scan = scan_instructions(module.funcs.get(fid).kind.unwrap_local());
536
537            let func_mut = module.funcs.get_mut(fid).kind.unwrap_local_mut();
538            patch_unreachables(func_mut, &mut scan.unreachables, flag_global, &return_types);
539            hook_calls(func_mut, &mut scan.calls, flag_global, &return_types);
540        }
541
542        // ── 5. Wrap entry-point exports ───────────────────────────────
543        // Created AFTER the instruction patching above so the wrappers
544        // themselves are not affected by the call-hook loop.
545        wrap_main_void(module, flag_global, fix_exit_code_import)?;
546        wrap_thread_start(module, flag_global, handle_thread_exit_import)?;
547
548        Ok(())
549    }
550}
551
552// ── Private helpers for `post_combine` ────────────────────────────────
553
554/// Returns the four helper function names that need import→export wiring
555/// during `post_combine`.
556///
557/// Because `WrapUnreachableName` requires a `&WasmName` reference and
558/// `post_combine` only has `String` target names, we look up the matching
559/// `WasmName` from the context to build properly typed names.
560fn helper_names_for(target: &str, target_names: &[WasmName]) -> Vec<String> {
561    if let Some(wn) = target_names.iter().find(|n| n.as_ref() == target) {
562        vec![
563            WrapUnreachableName::GetUnreachableFlag(wn).to_string(),
564            WrapUnreachableName::SetUnreachableFlag(wn).to_string(),
565            WrapUnreachableName::FixMainRawExitCode(wn).to_string(),
566            WrapUnreachableName::HandleThreadExit(wn).to_string(),
567        ]
568    } else {
569        vec![]
570    }
571}
572
573/// Returns the marker export name for a target during `post_combine`.
574fn marker_name_for(target: &str, target_names: &[WasmName]) -> String {
575    if let Some(wn) = target_names.iter().find(|n| n.as_ref() == target) {
576        WrapUnreachableName::WrapUnreachable(wn).to_string()
577    } else {
578        // Fallback to raw formatting if the WasmName is somehow missing.
579        format!("{}_{}_wrap_unreachable", WRAP_UNREACHABLE_MODULE, target)
580    }
581}