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
11const WRAP_UNREACHABLE_MODULE: &str = "__wasip1_virt_layer";
18
19#[derive(Debug, strum::AsRefStr, strum::EnumCount, Hash, PartialEq, Eq)]
28#[strum(serialize_all = "snake_case")]
29pub enum WrapUnreachableName<'a> {
30 WrapUnreachable(&'a WasmName),
32 GetUnreachableFlag(&'a WasmName),
34 SetUnreachableFlag(&'a WasmName),
36 FixMainRawExitCode(&'a WasmName),
38 HandleThreadExit(&'a WasmName),
40}
41
42impl WrapUnreachableName<'_> {
43 const PREFIX: &'static str = "__wasip1_virt_layer_";
45
46 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
67fn 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
85fn 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
98struct InstrScanResult {
102 unreachables: Vec<(InstrSeqId, usize)>,
104 calls: Vec<(InstrSeqId, usize)>,
106}
107
108fn 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
140fn 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
169fn 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 let loc = func.block(seq_id).instrs[idx].1;
187
188 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 let alternative_seq = func.builder_mut().dangling_instr_seq(None).id();
197
198 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
217fn 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
257fn 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
297fn 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
311fn 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
337fn 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#[derive(Debug, Default)]
379pub struct WrapUnreachableGenerator {
380 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 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 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 let flag_global = module.globals.add_local(
437 ValType::I32,
438 true,
439 false,
440 ConstExpr::Value(Value::I32(0)),
441 );
442
443 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 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 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 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
503fn 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
524fn 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 format!("{}_{}_wrap_unreachable", WRAP_UNREACHABLE_MODULE, target)
531 }
532}