Skip to main content

wasi_virt_layer_cli/generator/
wrap_unreachable.rs

1use std::collections::HashSet;
2
3use walrus::{ir::*, ConstExpr, ExportItem, FunctionId, Module, ValType};
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((Instr::Const(Const { value: dummy_value(ty) }), loc));
94    }
95    instrs.push((Instr::Return(Return {}), loc));
96}
97
98// ── Instruction scanning ──────────────────────────────────────────────
99
100/// Positions of interesting instructions found during a recursive scan.
101struct InstrScanResult {
102    /// `(seq_id, index)` pairs for `Unreachable` instructions.
103    unreachables: Vec<(InstrSeqId, usize)>,
104    /// `(seq_id, index)` pairs for `Call` / `CallIndirect` instructions.
105    calls: Vec<(InstrSeqId, usize)>,
106}
107
108/// Recursively walks every instruction sequence within `func`, recording
109/// positions of `unreachable` and `call` / `call_indirect` instructions.
110fn scan_instructions(func: &walrus::LocalFunction) -> InstrScanResult {
111    let mut result = InstrScanResult {
112        unreachables: Vec::new(),
113        calls: Vec::new(),
114    };
115
116    fn visit(
117        seq_id: InstrSeqId,
118        func: &walrus::LocalFunction,
119        result: &mut InstrScanResult,
120    ) {
121        for (i, (instr, _)) in func.block(seq_id).instrs.iter().enumerate() {
122            match instr {
123                Instr::Unreachable(_) => result.unreachables.push((seq_id, i)),
124                Instr::Call(_) | Instr::CallIndirect(_) => result.calls.push((seq_id, i)),
125                Instr::Block(b) => visit(b.seq, func, result),
126                Instr::Loop(l) => visit(l.seq, func, result),
127                Instr::IfElse(ie) => {
128                    visit(ie.consequent, func, result);
129                    visit(ie.alternative, func, result);
130                }
131                _ => {}
132            }
133        }
134    }
135
136    visit(func.entry_block(), func, &mut result);
137    result
138}
139
140// ── Instruction patching ──────────────────────────────────────────────
141
142/// Replaces every `unreachable` instruction at the recorded positions with
143/// a *set-flag + dummy-return* sequence.
144///
145/// Processes sites in reverse index order so that earlier indices remain valid.
146fn patch_unreachables(
147    func: &mut walrus::LocalFunction,
148    sites: &mut [(InstrSeqId, usize)],
149    flag_global: walrus::GlobalId,
150    return_types: &[ValType],
151) {
152    sites.sort_unstable_by(|a, b| b.cmp(a));
153
154    for &(seq_id, idx) in sites.iter() {
155        let seq = func.block_mut(seq_id);
156        let (_removed, loc) = seq.instrs.remove(idx);
157
158        let mut new_instrs = Vec::with_capacity(return_types.len() + 3);
159        new_instrs.push((Instr::Const(Const { value: Value::I32(1) }), loc));
160        new_instrs.push((Instr::GlobalSet(GlobalSet { global: flag_global }), loc));
161        push_dummy_return(&mut new_instrs, return_types, loc);
162
163        for (j, instr) in new_instrs.into_iter().enumerate() {
164            seq.instrs.insert(idx + j, instr);
165        }
166    }
167}
168
169/// Inserts a post-call flag-check after every `call` / `call_indirect` at the
170/// recorded positions.
171///
172/// The check is: `if (flag) { push dummy values; return; } else { /* nop */ }`.
173/// Processes sites in reverse index order.
174fn hook_calls(
175    func: &mut walrus::LocalFunction,
176    sites: &mut [(InstrSeqId, usize)],
177    flag_global: walrus::GlobalId,
178    return_types: &[ValType],
179) {
180    sites.sort_unstable_by(|a, b| b.cmp(a));
181
182    for &(seq_id, idx) in sites.iter() {
183        let insert_idx = idx + 1;
184
185        // Read the source location from the call instruction (NLL drops this borrow).
186        let loc = func.block(seq_id).instrs[idx].1;
187
188        // Build the consequent (flag-is-set) branch: dummy return.
189        let consequent_seq = func.builder_mut().dangling_instr_seq(None).id();
190        {
191            let consequent = func.block_mut(consequent_seq);
192            push_dummy_return(&mut consequent.instrs, return_types, loc);
193        }
194
195        // Empty alternative (flag-is-clear) branch.
196        let alternative_seq = func.builder_mut().dangling_instr_seq(None).id();
197
198        // Insert the check after the call.
199        let seq = func.block_mut(seq_id);
200        let check = [
201            (Instr::GlobalGet(GlobalGet { global: flag_global }), loc),
202            (
203                Instr::IfElse(IfElse {
204                    consequent: consequent_seq,
205                    alternative: alternative_seq,
206                }),
207                loc,
208            ),
209        ];
210
211        for (j, instr) in check.into_iter().enumerate() {
212            seq.instrs.insert(insert_idx + j, instr);
213        }
214    }
215}
216
217// ── Export wrapping ───────────────────────────────────────────────────
218
219/// Wraps the `__main_void` export so that, after calling the original
220/// function, the unreachable flag is checked and forwarded to
221/// `fix_main_raw_exit_code` when set.
222fn wrap_main_void(
223    module: &mut Module,
224    flag_global: walrus::GlobalId,
225    fix_exit_code_import: FunctionId,
226) -> eyre::Result<()> {
227    let Some((export_id, orig_func)) = find_export_func(module, "__main_void") else {
228        return Ok(());
229    };
230
231    let ret_local = module.locals.add(ValType::I32);
232    let wrapper = module.add_func(&[], &[ValType::I32], |builder, _| {
233        let mut body = builder.func_body();
234        body.call(orig_func);
235        body.local_set(ret_local);
236        body.global_get(flag_global);
237        body.if_else(
238            ValType::I32,
239            |then| {
240                then.global_get(flag_global);
241                then.call(fix_exit_code_import);
242            },
243            |else_| {
244                else_.local_get(ret_local);
245            },
246        );
247        Ok(())
248    })?;
249
250    module.exports.delete(export_id);
251    module.exports.add("__main_void", wrapper);
252    redirect_callers(module, orig_func, wrapper)?;
253
254    Ok(())
255}
256
257/// Wraps the `wasi_thread_start` export so that `handle_thread_exit` is
258/// invoked when the unreachable flag is set after the original entry point
259/// returns.
260fn wrap_thread_start(
261    module: &mut Module,
262    flag_global: walrus::GlobalId,
263    handle_thread_exit_import: FunctionId,
264) -> eyre::Result<()> {
265    let Some((export_id, orig_func)) = find_export_func(module, "wasi_thread_start") else {
266        return Ok(());
267    };
268
269    let wrapper = module.add_func(
270        &[ValType::I32, ValType::I32],
271        &[],
272        |builder, args| {
273            let mut body = builder.func_body();
274            body.local_get(args[0]);
275            body.local_get(args[1]);
276            body.call(orig_func);
277            body.global_get(flag_global);
278            body.if_else(
279                None,
280                |then| {
281                    then.global_get(flag_global);
282                    then.call(handle_thread_exit_import);
283                },
284                |_| {},
285            );
286            Ok(())
287        },
288    )?;
289
290    module.exports.delete(export_id);
291    module.exports.add("wasi_thread_start", wrapper);
292    redirect_callers(module, orig_func, wrapper)?;
293
294    Ok(())
295}
296
297// ── Shared utilities ──────────────────────────────────────────────────
298
299/// Finds a function export by name, returning its export ID and function ID.
300fn find_export_func(module: &Module, name: &str) -> Option<(walrus::ExportId, FunctionId)> {
301    module
302        .exports
303        .iter()
304        .find(|e| e.name == name)
305        .and_then(|e| match e.item {
306            ExportItem::Function(f) => Some((e.id(), f)),
307            _ => None,
308        })
309}
310
311/// Redirects all callers of `old_func` to `new_func`, **excluding** calls
312/// inside `new_func` itself (to prevent infinite recursion in wrappers).
313fn redirect_callers(
314    module: &mut Module,
315    old_func: FunctionId,
316    new_func: FunctionId,
317) -> eyre::Result<()> {
318    let all_fids: Vec<FunctionId> = module.funcs.iter_local().map(|(id, _)| id).collect();
319
320    for fid in all_fids {
321        if fid == new_func {
322            continue;
323        }
324        let local = module.funcs.get_mut(fid).kind.unwrap_local_mut();
325        local.builder_mut().func_body().rewrite(|instr, _| {
326            if let Instr::Call(call) = instr {
327                if call.func == old_func {
328                    call.func = new_func;
329                }
330            }
331        })?;
332    }
333
334    Ok(())
335}
336
337/// Wires an import to its matching export (by name) and removes the export.
338///
339/// Silently skipped when either the import or the export is absent — not every
340/// target exports every helper.
341fn wire_import_to_export(
342    module: &mut Module,
343    name: &str,
344    debug: bool,
345) -> eyre::Result<()> {
346    let Ok(import_fid) = (WRAP_UNREACHABLE_MODULE, name).get_fid(&module.imports) else {
347        return Ok(());
348    };
349    let Ok(export_fid) = name.get_fid(&module.exports) else {
350        return Ok(());
351    };
352
353    module.renew_call_fn(import_fid, export_fid)?;
354    module.exports.erase_with(export_fid, debug)?;
355
356    Ok(())
357}
358
359// ── Generator implementation ──────────────────────────────────────────
360
361/// Generator that replaces WebAssembly `unreachable` instructions and handles
362/// unwinding call stacks gracefully by injecting a global flag and modifying
363/// call sites.
364///
365/// When a VFS target module opts-in by exporting a
366/// `__wasip1_virt_layer_{target}_wrap_unreachable` marker (generated by the
367/// [`wrap_unreachable!`] macro), this generator:
368///
369/// 1. Adds a per-target global `unreachable_flag` to the target module.
370/// 2. Replaces every `unreachable` instruction with a flag-set + dummy-return
371///    sequence.
372/// 3. Hooks every `call` / `call_indirect` site with a post-call flag check
373///    that short-circuits with a dummy return when the flag is set.
374/// 4. Wraps `__main_void` and `wasi_thread_start` exports so the flag is
375///    forwarded to the VFS for proper exit-code / thread-exit handling.
376///
377/// [`wrap_unreachable!`]: wasi_virt_layer::wrap_unreachable
378#[derive(Debug, Default)]
379pub struct WrapUnreachableGenerator {
380    /// Target module names that opted in via the marker export.
381    targets: HashSet<String>,
382}
383
384impl Generator for WrapUnreachableGenerator {
385    fn pre_vfs(&mut self, module: &mut Module, ctx: &GeneratorCtx) -> eyre::Result<()> {
386        for target in ctx.target_names.iter() {
387            let marker = WrapUnreachableName::WrapUnreachable(&target).to_string();
388            if module.exports.iter().any(|e| e.name == marker) {
389                self.targets.insert(target.to_string());
390            }
391        }
392        Ok(())
393    }
394
395    fn post_combine(
396        &mut self,
397        module: &mut Module,
398        ctx: &GeneratorCtx,
399    ) -> eyre::Result<()> {
400        for target in &self.targets {
401            // Wire each helper import → export.
402            let helpers = helper_names_for(target, &ctx.target_names);
403            for name in &helpers {
404                wire_import_to_export(module, name, ctx.unstable_print_debug)?;
405            }
406
407            // Remove the opt-in marker export.
408            let marker = marker_name_for(target, &ctx.target_names);
409            if let Ok(fid) = marker.as_str().get_fid(&module.exports) {
410                module.exports.erase_with(fid, ctx.unstable_print_debug)?;
411            }
412        }
413        Ok(())
414    }
415
416    fn pre_target(
417        &mut self,
418        module: &mut Module,
419        _: &GeneratorCtx,
420        external: &ModuleExternal,
421    ) -> eyre::Result<()> {
422        if !self.targets.contains(&external.name.to_string()) {
423            return Ok(());
424        }
425
426        let get_flag_name =
427            WrapUnreachableName::GetUnreachableFlag(&external.name).to_string();
428        let set_flag_name =
429            WrapUnreachableName::SetUnreachableFlag(&external.name).to_string();
430        let fix_exit_code_name =
431            WrapUnreachableName::FixMainRawExitCode(&external.name).to_string();
432        let handle_exit_name =
433            WrapUnreachableName::HandleThreadExit(&external.name).to_string();
434
435        // ── 1. Per-target unreachable flag global ─────────────────────
436        let flag_global = module.globals.add_local(
437            ValType::I32,
438            true,
439            false,
440            ConstExpr::Value(Value::I32(0)),
441        );
442
443        // ── 2. Export getter / setter for the flag ────────────────────
444        let getter = module.add_func(&[], &[ValType::I32], |builder, _| {
445            builder.func_body().global_get(flag_global);
446            Ok(())
447        })?;
448        module.exports.add(&get_flag_name, getter);
449
450        let setter = module.add_func(&[ValType::I32], &[], |builder, args| {
451            builder
452                .func_body()
453                .local_get(args[0])
454                .global_set(flag_global);
455            Ok(())
456        })?;
457        module.exports.add(&set_flag_name, setter);
458
459        // ── 3. Import VFS handler functions ───────────────────────────
460        let fix_exit_code_ty = module.types.add(&[ValType::I32], &[ValType::I32]);
461        let fix_exit_code_import = module
462            .add_import_func(WRAP_UNREACHABLE_MODULE, &fix_exit_code_name, fix_exit_code_ty)
463            .0;
464
465        let handle_exit_ty = module.types.add(&[ValType::I32], &[]);
466        let handle_thread_exit_import = module
467            .add_import_func(WRAP_UNREACHABLE_MODULE, &handle_exit_name, handle_exit_ty)
468            .0;
469
470        // ── 4. Patch existing function instructions ───────────────────
471        // IMPORTANT: Must happen BEFORE creating wrapper functions below,
472        // so that the wrappers themselves are not processed by the
473        // call-hook loop. If the wrappers were processed, the hook after
474        // `call(orig_func)` would short-circuit with a dummy return,
475        // bypassing the fix_exit_code logic.
476        let func_ids: Vec<FunctionId> =
477            module.funcs.iter_local().map(|(id, _)| id).collect();
478
479        for fid in func_ids {
480            let return_types = module
481                .types
482                .get(module.funcs.get(fid).ty())
483                .results()
484                .to_vec();
485
486            let mut scan = scan_instructions(module.funcs.get(fid).kind.unwrap_local());
487
488            let func_mut = module.funcs.get_mut(fid).kind.unwrap_local_mut();
489            patch_unreachables(func_mut, &mut scan.unreachables, flag_global, &return_types);
490            hook_calls(func_mut, &mut scan.calls, flag_global, &return_types);
491        }
492
493        // ── 5. Wrap entry-point exports ───────────────────────────────
494        // Created AFTER the instruction patching above so the wrappers
495        // themselves are not affected by the call-hook loop.
496        wrap_main_void(module, flag_global, fix_exit_code_import)?;
497        wrap_thread_start(module, flag_global, handle_thread_exit_import)?;
498
499        Ok(())
500    }
501}
502
503// ── Private helpers for `post_combine` ────────────────────────────────
504
505/// Returns the four helper function names that need import→export wiring
506/// during `post_combine`.
507///
508/// Because `WrapUnreachableName` requires a `&WasmName` reference and
509/// `post_combine` only has `String` target names, we look up the matching
510/// `WasmName` from the context to build properly typed names.
511fn helper_names_for(target: &str, target_names: &[WasmName]) -> Vec<String> {
512    if let Some(wn) = target_names.iter().find(|n| n.as_ref() == target) {
513        vec![
514            WrapUnreachableName::GetUnreachableFlag(wn).to_string(),
515            WrapUnreachableName::SetUnreachableFlag(wn).to_string(),
516            WrapUnreachableName::FixMainRawExitCode(wn).to_string(),
517            WrapUnreachableName::HandleThreadExit(wn).to_string(),
518        ]
519    } else {
520        vec![]
521    }
522}
523
524/// Returns the marker export name for a target during `post_combine`.
525fn marker_name_for(target: &str, target_names: &[WasmName]) -> String {
526    if let Some(wn) = target_names.iter().find(|n| n.as_ref() == target) {
527        WrapUnreachableName::WrapUnreachable(wn).to_string()
528    } else {
529        // Fallback to raw formatting if the WasmName is somehow missing.
530        format!("{}_{}_wrap_unreachable", WRAP_UNREACHABLE_MODULE, target)
531    }
532}