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<()> {
228 let name = "debug_call_indirect";
229 if let Some(e) = get_fid(module, name)?.map(|fid| {
230 module
231 .debug_call_indirect(fid)
232 .wrap_err("Failed to set debug_call_indirect")?;
233
234 log::info!("{name} function found. Enabling debug feature.");
235
236 eyre::Ok(())
237 }) {
238 e.wrap_err("Failed to enable debug_call_indirect")?;
239 }
240
241 let name = "debug_atomic_wait";
242 if let Some(e) = get_fid(module, name)?.map(|fid| {
243 use walrus::ValType::{I32, I64};
244
245 log::info!("{name} function found. Enabling debug feature.");
246
247 module
248 .gen_inspect(fid, &[I32, I32, I64], &[fid], |instr| match instr {
249 walrus::ir::Instr::AtomicWait(_) => Some([]),
250 _ => None,
251 })
252 .wrap_err("Failed to set debug_atomic_wait")?;
253
254 eyre::Ok(())
255 }) {
256 e.wrap_err("Failed to enable debug_atomic_wait")?;
257 }
258
259 let name = "debug_loop";
260 if let Some(e) = get_fid(module, name)?.map(|fid| {
261 log::info!("{name} function found. Enabling debug feature.");
262
263 let mut count = 0;
264
265 module
266 .gen_inspect(fid, &[], &[fid], |instr| match instr {
267 walrus::ir::Instr::Loop(_) => Some([{
268 count += 1;
269 count
270 }]),
271 _ => None,
272 })
273 .wrap_err("Failed to set debug_loop")?;
274
275 eyre::Ok(())
276 }) {
277 e.wrap_err("Failed to enable debug_loop")?;
278 }
279
280 Ok(())
281}
282
283pub fn generate_debug_call_function_last(module: &mut walrus::Module) -> eyre::Result<()> {
284 use walrus::ir::*;
285 use walrus::*;
286
287 let name = "debug_call_function_start";
288
289 if let Some(e) = get_fid(module, name)?.map(|debugger| {
290 let excludes = gen_exclude_set(module).wrap_err("Failed to generate exclude set")?;
291
292 let finalize_name = "debug_call_function_end";
293 let finalize = get_fid(module, finalize_name)?.unwrap();
294
295 log::info!("{name}, {finalize_name} function found. Enabling debug feature.");
296
297 let import_count = module
298 .imports
299 .iter()
300 .filter(|imp| matches!(imp.kind, walrus::ImportKind::Function(_)))
301 .count();
302
303 let calc_future_size = |func: &LocalFunction, id: FunctionId| -> eyre::Result<u64> {
304 if excludes.contains(&id) {
305 Ok(func.size())
306 } else {
307 let mut size = func.size();
308 size += 2; size += 2; size += func
311 .read(|instr, _| {
312 if instr.is_return()
313 || instr.is_return_call()
314 || instr.is_return_call_indirect()
315 {
316 2u64
317 } else {
318 0
319 }
320 })
321 .wrap_err("Failed to read return instructions")?
322 .into_iter()
323 .sum::<u64>();
324 Ok(size)
325 }
326 };
327
328 let fids_with_size: HashMap<FunctionId, usize> = module
330 .funcs
331 .iter_local()
332 .map(|(fid, func)| {
333 calc_future_size(func, fid)
334 .wrap_err("Failed to calc size")
335 .map(|size| (fid, size as usize))
336 })
337 .collect::<eyre::Result<Vec<_>>>()?
338 .into_iter()
339 .sorted_by_key(|(id, size)| (cmp::Reverse(*size), *id))
340 .map(|(fid, _)| fid)
341 .enumerate()
342 .map(|(i, fid)| (fid, i + import_count))
343 .collect();
344
345 module
346 .funcs
347 .iter_local_mut()
348 .filter(|(func, _)| !excludes.contains(func))
349 .try_for_each(|(fid, func)| {
350 let fid = fids_with_size
351 .get(&fid)
352 .copied()
353 .wrap_err("Failed to get function order id")? as i32;
354 let entry_id = func.entry_block();
355 let mut body = func.builder_mut().func_body();
356 let mut entry_seq = body.instr_seq(entry_id);
357 {
358 entry_seq.const_at(0, Value::I32(fid));
359 entry_seq.call_at(1, debugger);
360 }
361
362 {
363 entry_seq.i32_const(fid).call(finalize);
365
366 let pos = body
367 .rewrite(|instr, pos| {
368 if instr.is_return()
369 || instr.is_return_call()
370 || instr.is_return_call_indirect()
371 {
372 Some(pos)
373 } else {
374 None
375 }
376 })
377 .map(|v| {
378 v.into_iter()
379 .filter_map(|v| v)
380 .sorted_by(|(a_pos, a_seq), (b_pos, b_seq)| {
381 b_seq.cmp(a_seq).then(b_pos.cmp(a_pos))
382 })
383 .collect_vec()
384 })
385 .wrap_err("Failed to find return instructions")?;
386
387 pos.into_iter().for_each(|(pos, seq)| {
388 let mut seq = body.instr_seq(seq);
389 seq.const_at(pos, Value::I32(fid))
390 .call_at(pos + 1, finalize);
391 });
392 }
393
394 eyre::Ok(())
395 })?;
396
397 eyre::Ok(())
398 }) {
399 e.wrap_err("Failed to enable debug_call_function")?;
400 }
401
402 Ok(())
403}
404
405pub fn has_debug(module: &walrus::Module) -> bool {
406 module
407 .exports
408 .iter()
409 .any(|export| EXCLUDE_NAMES.contains(&export.name.as_str()))
410}
411
412#[derive(Debug, Default)]
413pub struct DebugCallMemoryGrow {
414 has: Option<bool>,
415}
416
417impl Generator for DebugCallMemoryGrow {
418 fn pre_vfs(
419 &mut self,
420 module: &mut walrus::Module,
421 ctx: &crate::generator::GeneratorCtx,
422 ) -> eyre::Result<()> {
423 self.has = Some(false);
424
425 if !ctx.threads || !ctx.unstable_print_debug {
426 return Ok(());
427 }
428
429 if let Some((id, id2)) = "debug_call_memory_grow"
430 .get_fid(&module.exports)
431 .ok()
432 .and_then(|id| {
433 "debug_call_memory_grow_pre"
434 .get_fid(&module.exports)
435 .ok()
436 .map(|id2| (id, id2))
437 })
438 {
439 self.has = Some(true);
440
441 module
442 .gen_inspect_with_finalize(
443 Some(id),
444 Some(id2),
445 &[walrus::ValType::I32],
446 &[walrus::ValType::I32],
447 &module.funcs.find_children_with(id, false).unwrap(),
448 |instr| {
449 if let walrus::ir::Instr::MemoryGrow(walrus::ir::MemoryGrow {
450 memory: _,
451 ..
452 }) = instr
453 {
454 static mut Z: i32 = 17;
455 unsafe { Z += 1 };
456 Some([0, unsafe { Z }])
457 } else {
458 None
459 }
460 },
461 )
462 .unwrap();
463 }
464
465 Ok(())
466 }
467
468 fn pre_target(
469 &mut self,
470 module: &mut walrus::Module,
471 _: &crate::generator::GeneratorCtx,
472 _: &ModuleExternal,
473 ) -> eyre::Result<()> {
474 let has = self.has.wrap_err("DebugCallMemoryGrow not initialized")?;
475 if !has {
476 return Ok(());
477 }
478
479 let func_ty = module.types.add(
480 &[
481 walrus::ValType::I32,
482 walrus::ValType::I32,
483 walrus::ValType::I32,
484 ],
485 &[],
486 );
487 let (id, _) =
488 module.add_import_func("wasip1-vfs_debug", "debug_call_memory_grow_import", func_ty);
489 let (id2, _) = module.add_import_func(
490 "wasip1-vfs_debug",
491 "debug_call_memory_grow_pre_import",
492 func_ty,
493 );
494
495 module
496 .gen_inspect_with_finalize(
497 Some(id),
498 Some(id2),
499 &[walrus::ValType::I32],
500 &[walrus::ValType::I32],
501 &module.funcs.find_children_with(id, false).unwrap(),
502 |instr| {
503 if let walrus::ir::Instr::MemoryGrow(walrus::ir::MemoryGrow {
504 memory: _, ..
505 }) = instr
506 {
507 static mut I: i32 = 117;
508 unsafe { I += 1 };
509 println!("Rewriting memory.grow to call debug function");
510 Some([1, unsafe { I }])
511 } else {
512 None
513 }
514 },
515 )
516 .wrap_err("Failed to set debug_call_memory_grow")?;
517
518 Ok(())
519 }
520
521 fn post_combine(
522 &mut self,
523 module: &mut walrus::Module,
524 ctx: &crate::generator::GeneratorCtx,
525 ) -> eyre::Result<()> {
526 if !ctx.unstable_print_debug {
527 return Ok(());
528 }
529
530 module
531 .renew_call_fn(
532 ("wasip1-vfs_debug", "debug_call_memory_grow_import"),
533 "debug_call_memory_grow",
534 )
535 .ok();
536
537 module
538 .renew_call_fn(
539 ("wasip1-vfs_debug", "debug_call_memory_grow_pre_import"),
540 "debug_call_memory_grow_pre",
541 )
542 .ok();
543
544 Ok(())
545 }
546}
547
548#[derive(Debug, Default)]
549pub struct DebugExportVFSFunctions;
550
551impl Generator for DebugExportVFSFunctions {
552 fn pre_vfs(
553 &mut self,
554 module: &mut walrus::Module,
555 ctx: &crate::generator::GeneratorCtx,
556 ) -> eyre::Result<()> {
557 if !ctx.unstable_print_debug {
558 return Ok(());
559 }
560
561 for wasm_name in &ctx.target_names {
562 module
563 .exports
564 .iter()
565 .filter(|export| {
566 export
567 .name
568 .starts_with(&format!("__wasip1_vfs_{wasm_name}_"))
569 })
570 .filter(|export| {
571 <Wasip1ABIFunc as strum::VariantNames>::VARIANTS.contains(
572 &export
573 .name
574 .as_str()
575 .trim_start_matches(&format!("__wasip1_vfs_{wasm_name}_")),
576 )
577 })
578 .filter_map(|export| match export.item {
579 walrus::ExportItem::Function(fid) => Some((export.name.clone(), fid)),
580 _ => None,
581 })
582 .collect::<Vec<_>>()
583 .into_iter()
584 .for_each(|(name, old_fid)| {
585 module.exports.add(&format!("debug_{name}"), old_fid);
586 });
587 }
588
589 Ok(())
590 }
591}
592
593#[derive(Debug, Default)]
594pub struct DebugBase;
595
596impl Generator for DebugBase {
597 fn post_combine(
598 &mut self,
599 module: &mut walrus::Module,
600 ctx: &crate::generator::GeneratorCtx,
601 ) -> eyre::Result<()> {
602 if !ctx.unstable_print_debug {
603 return Ok(());
604 }
605
606 if let Some(id) = "debug_wasip1_vfs_pre_init".get_fid(&module.exports).ok() {
607 let start = module.funcs.get_mut(module.start.unwrap());
608 start
609 .kind
610 .unwrap_local_mut()
611 .builder_mut()
612 .func_body()
613 .call(id);
614 }
615
616 Ok(())
617 }
618}
619
620#[derive(Debug, Default)]
621pub struct DebugCallFunctionSmallScale;
622
623impl Generator for DebugCallFunctionSmallScale {
624 fn post_all_optimize(
625 &mut self,
626 module: &mut walrus::Module,
627 ctx: &super::ComponentCtx,
628 ) -> eyre::Result<bool> {
629 if !ctx.unstable_print_debug() {
630 return Ok(false);
631 }
632
633 generate_debug_call_function(module).wrap_err("Failed to generate debug_call_function")?;
634
635 Ok(true)
636 }
637}
638
639#[derive(Debug, Default)]
640pub struct DebugCallFunctionMain;
641
642impl Generator for DebugCallFunctionMain {
643 fn post_all_optimize(
644 &mut self,
645 module: &mut walrus::Module,
646 ctx: &super::ComponentCtx,
647 ) -> eyre::Result<bool> {
648 if !ctx.unstable_print_debug() {
649 return Ok(false);
650 }
651
652 generate_debug_call_function_last(module)
653 .wrap_err("Failed to generate debug_call_function_last")?;
654
655 Ok(true)
656 }
657}