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, 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((
94 Instr::Const(Const {
95 value: dummy_value(ty),
96 }),
97 loc,
98 ));
99 }
100 instrs.push((Instr::Return(Return {}), loc));
101}
102
103struct InstrScanResult {
107 unreachables: Vec<(InstrSeqId, usize)>,
109 calls: Vec<(InstrSeqId, usize)>,
111}
112
113fn 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
160fn 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
199fn 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 let loc = func.block(seq_id).instrs[idx].1;
217
218 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 let alternative_seq = func.builder_mut().dangling_instr_seq(None).id();
227
228 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
252fn 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
292fn 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
328fn 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
342fn 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
368fn 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 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#[derive(Debug, Default)]
426pub struct WrapUnreachableGenerator {
427 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 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 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 let flag_global =
485 module
486 .globals
487 .add_local(ValType::I32, true, false, ConstExpr::Value(Value::I32(0)));
488
489 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 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 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 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
552fn 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
573fn 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 format!("{}_{}_wrap_unreachable", WRAP_UNREACHABLE_MODULE, target)
580 }
581}