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