1use std::{cmp, collections::HashMap};
2
3use eyre::{Context as _, ContextCompat as _};
4use itertools::Itertools;
5
6use crate::{
7 abi::Wasip1ABIFunc,
8 generator::{Generator, ModuleExternal},
9 instrs::{InstrRead as _, InstrRewrite},
10 util::{WalrusFID, WalrusUtilFuncs as _, WalrusUtilModule as _},
11};
12
13macro_rules! get_instr {
14 ($seq:expr, $idx:expr) => {{
15 let length = $seq.instrs().len();
16 #[allow(unused_comparisons)]
17 let idx = if $idx < 0 {
18 length as isize + $idx as isize
19 } else {
20 $idx as isize
21 } as usize;
22 $seq.instrs().get(idx).map(|(i, _)| i.clone())
23 }};
24}
25
26pub fn readjust_debug_call_function(module: &mut walrus::Module) -> eyre::Result<bool> {
28 let mut changed = 0;
29
30 let debugger = "debug_call_function_start".get_fid(&module.exports)?;
31
32 let finalize = "debug_call_function_end".get_fid(&module.exports)?;
33
34 let excludes = gen_exclude_set(module).wrap_err("Failed to generate exclude set")?;
35
36 module
37 .funcs
38 .iter_local_mut()
39 .filter(|(func, _)| !excludes.contains(func))
40 .try_for_each(|(fid, func)| {
41 use walrus::ir::*;
42
43 let fid = fid.index() as i32;
44
45 let entry_id = func.entry_block();
47 let mut body = func.builder_mut().func_body();
48 let mut entry_seq = body.instr_seq(entry_id);
49
50 let len = entry_seq.instrs().len();
54 let ret_trap = entry_seq
55 .rewrite(|instr, (pos, seq_id)| {
56 if instr.is_return()
57 || instr.is_return_call()
58 || instr.is_return_call_indirect()
59 {
60 Some((pos, seq_id))
61 } else {
62 None
63 }
64 })?
65 .into_iter()
66 .filter_map(|v| v)
67 .sorted_by(|(a_pos, a_seq), (b_pos, b_seq)| b_seq.cmp(a_seq).then(b_pos.cmp(a_pos)))
68 .collect_vec();
69
70 {
71 entry_seq.rewrite(|instr, (pos, seq_id)| {
72 if ret_trap
73 .iter()
74 .filter(|(_, s)| *s == seq_id)
75 .any(|(p, _)| pos == *p - 1)
76 {
77 return;
78 }
79
80 if let Instr::Call(Call { func }) = instr
81 && ((*func == debugger && seq_id == entry_id && pos != 1)
82 || (*func == finalize && seq_id != entry_id && pos != len - 1))
83 {
84 *instr = Instr::Drop(Drop {});
85 changed += 1;
86 }
88 })?;
89 }
90
91 let adjust_common =
92 |seq: &mut walrus::InstrSeqBuilder<'_>,
93 pos: usize,
94 caller|
95 -> eyre::Result<(Option<i32>, Option<walrus::FunctionId>)> {
96 let before = match get_instr!(seq, pos) {
97 Some(Instr::Const(Const {
98 value: Value::I32(value),
99 })) if value == fid => Some(value),
100 _ => None,
101 };
102 let after = match get_instr!(seq, pos + 1) {
103 Some(Instr::Call(Call { func })) if func == caller => Some(func),
104 _ => None,
105 };
106
107 Ok((before, after))
108 };
109
110 let mut adjust_front = |seq_id: InstrSeqId, pos: usize, caller| {
111 let mut seq = body.instr_seq(seq_id);
112 let (before, after) = adjust_common(&mut seq, pos, caller)?;
113 match (before, after) {
117 (Some(_), Some(_)) => {}
118 (None, None) => {
119 seq.const_at(pos + 2, Value::I32(fid));
121 seq.call_at(pos + 3, caller);
122 changed += 1;
123 }
124 (None, Some(_)) => {
125 seq.instrs_mut().remove(pos);
127 seq.const_at(pos, Value::I32(fid));
128 changed += 1;
129 }
130 (Some(_), None) => {
131 seq.instrs_mut().remove(pos + 1);
133 seq.call_at(pos + 1, caller);
134 changed += 1;
135 }
136 }
137 eyre::Ok(())
138 };
139
140 adjust_front(entry_id, len - 2, finalize)?;
141 for (pos, seq) in ret_trap.into_iter() {
142 adjust_front(seq, pos - 2, finalize)?;
143 }
144
145 let mut adjust_first = |seq_id: InstrSeqId, pos: usize, caller| {
146 let mut seq = body.instr_seq(seq_id);
147 let (before, after) = adjust_common(&mut seq, pos, caller)?;
148 match (before, after) {
152 (Some(_), Some(_)) => {}
153 (None, None) => {
154 seq.const_at(pos, Value::I32(fid));
156 seq.call_at(pos + 1, caller);
157 changed += 1;
158 }
159 (None, Some(_)) => {
160 seq.instrs_mut().remove(pos);
162 seq.const_at(pos, Value::I32(fid));
163 changed += 1;
164 }
165 (Some(_), None) => {
166 seq.instrs_mut().remove(pos + 1);
168 seq.call_at(pos + 1, caller);
169 changed += 1;
170 }
171 }
172 eyre::Ok(())
173 };
174
175 adjust_first(entry_id, 0, debugger)?;
176
177 eyre::Ok(())
178 })?;
179
180 eprintln!("Readjusted debug_call_function, changes made: {changed}");
181
182 Ok(changed != 0)
183}
184
185const EXCLUDE_NAMES: &[&str] = &[
186 "debug_call_indirect",
187 "debug_atomic_wait",
188 "debug_call_function_start",
189 "debug_call_function_end",
190 "debug_blind_print_etc_flag",
191 "debug_loop",
192];
193
194fn gen_exclude_set(module: &mut walrus::Module) -> eyre::Result<Vec<walrus::FunctionId>> {
195 let start = module.start;
196
197 [
198 "debug_call_function_start",
199 "debug_call_function_end",
200 "debug_loop",
201 ]
202 .iter()
203 .filter_map(|name| get_fid(module, name).transpose())
204 .chain(start.iter().copied().map(Ok))
205 .collect::<eyre::Result<Vec<_>>>()?
206 .into_iter()
207 .map(|fid| module.funcs.find_children_with(fid, false))
208 .flatten_ok()
209 .try_collect::<_, Vec<_>, _>()
210}
211
212fn get_fid(module: &mut walrus::Module, name: &str) -> eyre::Result<Option<walrus::FunctionId>> {
213 module
214 .exports
215 .iter()
216 .find(|export| export.name == name)
217 .map(|export| {
218 let fid = match export.item {
219 walrus::ExportItem::Function(fid) => fid,
220 _ => eyre::bail!("{name} is not a function export"),
221 };
222 Ok(fid)
223 })
224 .transpose()
225}
226
227pub fn generate_debug_call_function(module: &mut walrus::Module) -> eyre::Result<()> {
229 let name = "debug_call_indirect";
230 if let Some(e) = get_fid(module, name)?.map(|fid| {
231 module
232 .debug_call_indirect(fid)
233 .wrap_err("Failed to set debug_call_indirect")?;
234
235 log::info!("{name} function found. Enabling debug feature.");
236
237 eyre::Ok(())
238 }) {
239 e.wrap_err("Failed to enable debug_call_indirect")?;
240 }
241
242 let name = "debug_atomic_wait";
243 if let Some(e) = get_fid(module, name)?.map(|fid| {
244 use walrus::ValType::{I32, I64};
245
246 log::info!("{name} function found. Enabling debug feature.");
247
248 module
249 .gen_inspect(fid, &[I32, I32, I64], &[fid], |instr| match instr {
250 walrus::ir::Instr::AtomicWait(_) => Some([]),
251 _ => None,
252 })
253 .wrap_err("Failed to set debug_atomic_wait")?;
254
255 eyre::Ok(())
256 }) {
257 e.wrap_err("Failed to enable debug_atomic_wait")?;
258 }
259
260 let name = "debug_loop";
261 if let Some(e) = get_fid(module, name)?.map(|fid| {
262 log::info!("{name} function found. Enabling debug feature.");
263
264 let mut count = 0;
265
266 module
267 .gen_inspect(fid, &[], &[fid], |instr| match instr {
268 walrus::ir::Instr::Loop(_) => Some([{
269 count += 1;
270 count
271 }]),
272 _ => None,
273 })
274 .wrap_err("Failed to set debug_loop")?;
275
276 eyre::Ok(())
277 }) {
278 e.wrap_err("Failed to enable debug_loop")?;
279 }
280
281 Ok(())
282}
283
284pub fn generate_debug_call_function_last(module: &mut walrus::Module) -> eyre::Result<()> {
286 use walrus::ir::*;
287 use walrus::*;
288
289 let name = "debug_call_function_start";
290
291 if let Some(e) = get_fid(module, name)?.map(|debugger| {
292 let excludes = gen_exclude_set(module).wrap_err("Failed to generate exclude set")?;
293
294 let finalize_name = "debug_call_function_end";
295 let finalize = get_fid(module, finalize_name)?.unwrap();
296
297 log::info!("{name}, {finalize_name} function found. Enabling debug feature.");
298
299 let import_count = module
300 .imports
301 .iter()
302 .filter(|imp| matches!(imp.kind, walrus::ImportKind::Function(_)))
303 .count();
304
305 let calc_future_size = |func: &LocalFunction, id: FunctionId| -> eyre::Result<u64> {
306 if excludes.contains(&id) {
307 Ok(func.size())
308 } else {
309 let mut size = func.size();
310 size += 2; size += 2; size += func
313 .read(|instr, _| {
314 if instr.is_return()
315 || instr.is_return_call()
316 || instr.is_return_call_indirect()
317 {
318 2u64
319 } else {
320 0
321 }
322 })
323 .wrap_err("Failed to read return instructions")?
324 .into_iter()
325 .sum::<u64>();
326 Ok(size)
327 }
328 };
329
330 let fids_with_size: HashMap<FunctionId, usize> = module
332 .funcs
333 .iter_local()
334 .map(|(fid, func)| {
335 calc_future_size(func, fid)
336 .wrap_err("Failed to calc size")
337 .map(|size| (fid, size as usize))
338 })
339 .collect::<eyre::Result<Vec<_>>>()?
340 .into_iter()
341 .sorted_by_key(|(id, size)| (cmp::Reverse(*size), *id))
342 .map(|(fid, _)| fid)
343 .enumerate()
344 .map(|(i, fid)| (fid, i + import_count))
345 .collect();
346
347 module
348 .funcs
349 .iter_local_mut()
350 .filter(|(func, _)| !excludes.contains(func))
351 .try_for_each(|(fid, func)| {
352 let fid = fids_with_size
353 .get(&fid)
354 .copied()
355 .wrap_err("Failed to get function order id")? as i32;
356 let entry_id = func.entry_block();
357 let mut body = func.builder_mut().func_body();
358 let mut entry_seq = body.instr_seq(entry_id);
359 {
360 entry_seq.const_at(0, Value::I32(fid));
361 entry_seq.call_at(1, debugger);
362 }
363
364 {
365 entry_seq.i32_const(fid).call(finalize);
367
368 let pos = body
369 .rewrite(|instr, pos| {
370 if instr.is_return()
371 || instr.is_return_call()
372 || instr.is_return_call_indirect()
373 {
374 Some(pos)
375 } else {
376 None
377 }
378 })
379 .map(|v| {
380 v.into_iter()
381 .filter_map(|v| v)
382 .sorted_by(|(a_pos, a_seq), (b_pos, b_seq)| {
383 b_seq.cmp(a_seq).then(b_pos.cmp(a_pos))
384 })
385 .collect_vec()
386 })
387 .wrap_err("Failed to find return instructions")?;
388
389 pos.into_iter().for_each(|(pos, seq)| {
390 let mut seq = body.instr_seq(seq);
391 seq.const_at(pos, Value::I32(fid))
392 .call_at(pos + 1, finalize);
393 });
394 }
395
396 eyre::Ok(())
397 })?;
398
399 eyre::Ok(())
400 }) {
401 e.wrap_err("Failed to enable debug_call_function")?;
402 }
403
404 Ok(())
405}
406
407pub fn has_debug(module: &walrus::Module) -> bool {
409 module
410 .exports
411 .iter()
412 .any(|export| EXCLUDE_NAMES.contains(&export.name.as_str()))
413}
414
415#[derive(Debug, Default)]
416pub struct DebugCallMemoryGrow {
418 has: Option<bool>,
419}
420
421impl Generator for DebugCallMemoryGrow {
422 fn pre_vfs(
423 &mut self,
424 module: &mut walrus::Module,
425 ctx: &crate::generator::GeneratorCtx,
426 ) -> eyre::Result<()> {
427 self.has = Some(false);
428
429 if !ctx.threads || !ctx.unstable_print_debug {
430 return Ok(());
431 }
432
433 if let Some((id, id2)) = "debug_call_memory_grow"
434 .get_fid(&module.exports)
435 .ok()
436 .and_then(|id| {
437 "debug_call_memory_grow_pre"
438 .get_fid(&module.exports)
439 .ok()
440 .map(|id2| (id, id2))
441 })
442 {
443 self.has = Some(true);
444
445 module
446 .gen_inspect_with_finalize(
447 Some(id),
448 Some(id2),
449 &[walrus::ValType::I32],
450 &[walrus::ValType::I32],
451 &module.funcs.find_children_with(id, false).unwrap(),
452 |instr| {
453 if let walrus::ir::Instr::MemoryGrow(walrus::ir::MemoryGrow {
454 memory: _,
455 ..
456 }) = instr
457 {
458 static mut Z: i32 = 17;
459 unsafe { Z += 1 };
460 Some([0, unsafe { Z }])
461 } else {
462 None
463 }
464 },
465 )
466 .unwrap();
467 }
468
469 Ok(())
470 }
471
472 fn pre_target(
473 &mut self,
474 module: &mut walrus::Module,
475 _: &crate::generator::GeneratorCtx,
476 _: &ModuleExternal,
477 ) -> eyre::Result<()> {
478 let has = self.has.wrap_err("DebugCallMemoryGrow not initialized")?;
479 if !has {
480 return Ok(());
481 }
482
483 let func_ty = module.types.add(
484 &[
485 walrus::ValType::I32,
486 walrus::ValType::I32,
487 walrus::ValType::I32,
488 ],
489 &[],
490 );
491 let (id, _) =
492 module.add_import_func("wasip1-vfs_debug", "debug_call_memory_grow_import", func_ty);
493 let (id2, _) = module.add_import_func(
494 "wasip1-vfs_debug",
495 "debug_call_memory_grow_pre_import",
496 func_ty,
497 );
498
499 module
500 .gen_inspect_with_finalize(
501 Some(id),
502 Some(id2),
503 &[walrus::ValType::I32],
504 &[walrus::ValType::I32],
505 &module.funcs.find_children_with(id, false).unwrap(),
506 |instr| {
507 if let walrus::ir::Instr::MemoryGrow(walrus::ir::MemoryGrow {
508 memory: _, ..
509 }) = instr
510 {
511 static mut I: i32 = 117;
512 unsafe { I += 1 };
513 println!("Rewriting memory.grow to call debug function");
514 Some([1, unsafe { I }])
515 } else {
516 None
517 }
518 },
519 )
520 .wrap_err("Failed to set debug_call_memory_grow")?;
521
522 Ok(())
523 }
524
525 fn post_combine(
526 &mut self,
527 module: &mut walrus::Module,
528 ctx: &crate::generator::GeneratorCtx,
529 ) -> eyre::Result<()> {
530 if !ctx.unstable_print_debug {
531 return Ok(());
532 }
533
534 module
535 .renew_call_fn(
536 ("wasip1-vfs_debug", "debug_call_memory_grow_import"),
537 "debug_call_memory_grow",
538 )
539 .ok();
540
541 module
542 .renew_call_fn(
543 ("wasip1-vfs_debug", "debug_call_memory_grow_pre_import"),
544 "debug_call_memory_grow_pre",
545 )
546 .ok();
547
548 Ok(())
549 }
550}
551
552#[derive(Debug, Default)]
553pub struct DebugExportVFSFunctions;
555
556impl Generator for DebugExportVFSFunctions {
557 fn pre_vfs(
558 &mut self,
559 module: &mut walrus::Module,
560 ctx: &crate::generator::GeneratorCtx,
561 ) -> eyre::Result<()> {
562 if !ctx.unstable_print_debug {
563 return Ok(());
564 }
565
566 for wasm_name in &ctx.target_names {
567 module
568 .exports
569 .iter()
570 .filter(|export| {
571 export
572 .name
573 .starts_with(&format!("__wasip1_vfs_{wasm_name}_"))
574 })
575 .filter(|export| {
576 <Wasip1ABIFunc as strum::VariantNames>::VARIANTS.contains(
577 &export
578 .name
579 .as_str()
580 .trim_start_matches(&format!("__wasip1_vfs_{wasm_name}_")),
581 )
582 })
583 .filter_map(|export| match export.item {
584 walrus::ExportItem::Function(fid) => Some((export.name.clone(), fid)),
585 _ => None,
586 })
587 .collect::<Vec<_>>()
588 .into_iter()
589 .for_each(|(name, old_fid)| {
590 module.exports.add(&format!("debug_{name}"), old_fid);
591 });
592 }
593
594 Ok(())
595 }
596}
597
598#[derive(Debug, Default)]
599pub struct SimpleDebug;
601
602impl Generator for SimpleDebug {
603 fn post_combine(
604 &mut self,
605 module: &mut walrus::Module,
606 ctx: &crate::generator::GeneratorCtx,
607 ) -> eyre::Result<()> {
608 if let Some(id) = "simple_debug_wasip1_vfs_pre_init"
609 .get_fid(&module.exports)
610 .ok()
611 {
612 let space = ctx
613 .starts
614 .simple_debug_wasip1_vfs_pre_init
615 .get_fid(&module.exports)?;
616 let start = module.funcs.get_mut(space);
617 start
618 .kind
619 .unwrap_local_mut()
620 .builder_mut()
621 .func_body()
622 .call(id);
623 }
624
625 Ok(())
626 }
627}
628
629#[derive(Debug, Default)]
630pub struct DebugCallFunctionSmallScale;
632
633impl Generator for DebugCallFunctionSmallScale {
634 fn post_all_optimize(
635 &mut self,
636 module: &mut walrus::Module,
637 ctx: &super::ComponentCtx,
638 ) -> eyre::Result<bool> {
639 if !ctx.unstable_print_debug() {
640 return Ok(false);
641 }
642
643 generate_debug_call_function(module).wrap_err("Failed to generate debug_call_function")?;
644
645 Ok(true)
646 }
647}
648
649#[derive(Debug, Default)]
650pub struct DebugCallFunctionMain;
652
653impl Generator for DebugCallFunctionMain {
654 fn post_all_optimize(
655 &mut self,
656 module: &mut walrus::Module,
657 ctx: &super::ComponentCtx,
658 ) -> eyre::Result<bool> {
659 if !ctx.unstable_print_debug() {
660 return Ok(false);
661 }
662
663 generate_debug_call_function_last(module)
664 .wrap_err("Failed to generate debug_call_function_last")?;
665
666 Ok(true)
667 }
668}