wasi_virt_layer_cli/generator/
special_func.rs1use std::collections::HashSet;
2
3use eyre::Context as _;
4use walrus::*;
5
6use crate::{
7 generator::{Generator, GeneratorCtx, ModuleExternal},
8 instrs::InstrRewrite as _,
9 unique_name::UniqueName,
10 util::{ResultUtil as _, WalrusFID, WalrusUtilFuncs as _, WalrusUtilModule as _, WasmName},
11};
12
13#[derive(Debug, strum::AsRefStr, strum::EnumCount, Hash, PartialEq, Eq)]
15#[strum(serialize_all = "snake_case")]
16pub enum SpecialFuncUniqueName<'a> {
17 Resetter(&'a WasmName),
19 ResetOnThread,
21 ResetOnThreadOnce,
23 StartInitOld,
25 Start(&'a WasmName),
27 MainVoid(&'a WasmName),
29 Reset(&'a WasmName),
31}
32
33pub struct VFSExternalMemoryManager {
37 external_size: usize,
38 current_size: usize, mem_id: MemoryId,
40}
41
42impl VFSExternalMemoryManager {
43 pub fn new(module: &mut walrus::Module) -> Self {
45 let mem_id = module.memories.add_local(true, false, 0, None, None);
46
47 Self {
48 external_size: 0,
49 current_size: 0,
50 mem_id,
51 }
52 }
53
54 pub fn memory_id(&self) -> MemoryId {
56 self.mem_id
57 }
58
59 pub fn alloc(&mut self, size: usize) -> usize {
61 let ptr = self.current_size * 64 * 1024 + self.external_size;
62 self.external_size += size;
63
64 ptr
65 }
66
67 pub fn flush(mut self, module: &mut walrus::Module, threads: bool) -> eyre::Result<MemoryId> {
69 let external_size = (0..=0x10000)
70 .find(|i| *i * 64 * 1024 >= self.external_size)
71 .ok_or_else(|| eyre::eyre!("Failed to find external size in 0..=0x10000"))?;
72
73 self.current_size += external_size;
74
75 let mem = module.memories.get_mut(self.mem_id);
76
77 mem.initial = self.current_size as u64;
78 mem.shared = threads;
79
80 if threads {
81 mem.maximum = Some(mem.initial);
82 }
83
84 Ok(self.mem_id)
85 }
86}
87
88#[derive(Debug, Default)]
90pub struct ResetFunc;
91
92impl Generator for ResetFunc {
93 fn post_combine(
94 &mut self,
95 module: &mut walrus::Module,
96 ctx: &GeneratorCtx,
97 ) -> eyre::Result<()> {
98 let mut mem_manager = VFSExternalMemoryManager::new(module);
99
100 let initializers = module
101 .add_func(&[], &[], |_, _| Ok(()))
102 .wrap_err_with(|| eyre::eyre!("Failed to add initializer function"))?;
103
104 let tmp_start_section_id = module.add_func(&[], &[], |_, _| Ok(()))?;
105
106 for wasm in &ctx.target_names {
107 let wasm_mem = ctx.target_used_memory_id.as_ref().unwrap()[wasm];
108
109 if let Some(reset) = (
110 UniqueName::NAMESPACE,
111 &UniqueName::SpecialFunc(&SpecialFuncUniqueName::Reset(wasm)),
112 )
113 .get_fid(&module.imports)
114 .ok()
115 {
116 let global = ctx.target_used_global_id.as_ref().unwrap()[wasm]
117 .iter()
118 .copied()
119 .map(|g| module.globals.get(g))
120 .filter(|g| g.mutable)
121 .filter_map(|g| {
122 if let GlobalKind::Local(ConstExpr::Value(v)) = g.kind {
123 Some((g.id(), v.clone()))
124 } else {
125 log::warn!(
126 "Global segment {:?} is not a value, we support only local variables",
127 g.kind
128 );
129 None
130 }
131 })
132 .collect::<Box<_>>();
133
134 let data_range = module
135 .data
136 .iter()
137 .filter_map(|data| {
138 match &data.kind {
139 DataKind::Active { memory, offset } if *memory == wasm_mem => {
140 if let ConstExpr::Value(v) = offset {
141 if let ir::Value::I32(offset) = v {
142 Some((*offset, data.value.len()))
143 } else {
144 log::warn!(
145 "Data segment {:?} is not i32, we support only i32",
146 offset
147 );
148 None
149 }
150 } else {
151 log::warn!(
152 "Data segment {:?} is not a value, we support only i32",
153 offset
154 );
155 None
156 }
157 }
158 _ => None,
160 }
161 })
162 .collect::<Box<_>>();
163
164 let zero_range = std::iter::once(Some(0i32))
165 .chain(
166 data_range
167 .iter()
168 .flat_map(|(offset, len)| [Some(*offset), Some(*offset + *len as i32)]),
169 )
170 .chain(std::iter::once(None))
171 .collect::<Vec<_>>()
172 .chunks(2)
173 .map(|chunk| (chunk[0].unwrap(), chunk[1]))
174 .collect::<Box<_>>();
175
176 let mem_init = data_range
177 .into_iter()
178 .map(|(offset, len)| (offset, len, mem_manager.alloc(len)))
179 .collect::<Box<_>>();
180
181 let reset_area_mem_id = mem_manager.memory_id();
182
183 let resetter = module
184 .replace_imported_func(reset, |(builder, _)| {
185 let mut body = builder.func_body();
186
187 for (id, value) in global.iter() {
188 body.const_(*value).global_set(*id);
189 }
190 for (start, end) in zero_range.iter() {
191 body.i32_const(*start)
193 .i32_const(0);
195
196 if let Some(end) = end {
198 body.i32_const(*end - *start);
199 } else {
200 body.memory_size(wasm_mem);
201
202 body.i32_const(64 * 1024)
205 .binop(ir::BinaryOp::I32Mul)
206 .i32_const(*start)
207 .binop(ir::BinaryOp::I32Sub);
208 }
209 body.memory_fill(wasm_mem);
210 }
211 for (mem_offset, mem_len, mem_ptr) in mem_init.iter() {
212 body.i32_const(*mem_offset) .i32_const(*mem_ptr as i32) .i32_const(*mem_len as i32) .memory_copy(reset_area_mem_id, wasm_mem);
216 }
217
218 body.call(tmp_start_section_id);
219 })
220 .to_eyre()
221 .wrap_err_with(|| eyre::eyre!("Failed to replace reset function for {wasm}"))?;
222
223 if ctx.unstable_print_debug {
224 module.exports.add(
225 &UniqueName::SpecialFunc(&SpecialFuncUniqueName::Resetter(wasm))
226 .to_string(),
227 resetter,
228 );
229 }
230
231 let mut func_body = module
232 .funcs
233 .get_mut(initializers)
234 .kind
235 .unwrap_local_mut()
236 .builder_mut()
237 .func_body();
238
239 for (offset, len, ptr) in mem_init {
240 func_body
241 .i32_const(ptr as i32) .i32_const(offset) .i32_const(len as i32) .memory_copy(wasm_mem, reset_area_mem_id);
245 }
246 }
247 }
248
249 let _ = mem_manager.flush(module, ctx.threads)?;
250
251 let init_id = if ctx.threads {
255 let reset_on_thread = UniqueName::SpecialFunc(&SpecialFuncUniqueName::ResetOnThread)
256 .get_fid(&module.exports)?;
257 let reset_on_thread_once = (
258 UniqueName::NAMESPACE,
259 &UniqueName::SpecialFunc(&SpecialFuncUniqueName::ResetOnThreadOnce),
260 )
261 .get_fid(&module.imports)?;
262
263 module.renew_call_fn(reset_on_thread_once, initializers)?;
269
270 reset_on_thread
271 } else {
272 initializers
273 };
274
275 let old_start = module.start.clone();
276 let new_start = module
277 .add_func(&[], &[], |builder, _| {
278 let mut body = builder.func_body();
279 body.call(init_id); if let Some(old_start) = old_start {
281 body.call(old_start);
282 }
283 Ok(())
284 })
285 .wrap_err_with(|| eyre::eyre!("Failed to add new start function"))?;
286
287 module.start = Some(new_start);
288
289 module.renew_call_fn(tmp_start_section_id, new_start)?;
290
291 if let Some(start) = old_start {
292 if ctx.unstable_print_debug {
293 module.exports.add(
294 &UniqueName::SpecialFunc(&SpecialFuncUniqueName::StartInitOld).to_string(),
295 start,
296 );
297 }
298 }
299
300 module
307 .funcs
308 .iter_mut()
309 .map(|func| {
310 match &mut func.kind {
311 walrus::FunctionKind::Local(l) => {
312 l.builder_mut()
313 .func_body()
314 .retain(|instr, _| !instr.is_data_drop());
315 }
316 _ => {}
317 }
318 Ok(())
319 })
320 .collect::<eyre::Result<Vec<_>>>()?;
321
322 Ok(())
323 }
324}
325
326#[derive(Debug, Default)]
328pub struct StartFunc;
329
330impl Generator for StartFunc {
331 fn pre_target(
332 &mut self,
333 module: &mut walrus::Module,
334 _: &GeneratorCtx,
335 external: &ModuleExternal,
336 ) -> eyre::Result<()> {
337 let id = "_start".get_fid(&module.exports)?;
338
339 module
340 .exports
341 .get_mut(module.exports.get_exported_func(id).unwrap().id())
342 .name =
343 UniqueName::SpecialFunc(&SpecialFuncUniqueName::Start(&external.name)).to_string();
344
345 Ok(())
346 }
347
348 fn post_combine(
349 &mut self,
350 module: &mut walrus::Module,
351 ctx: &GeneratorCtx,
352 ) -> eyre::Result<()> {
353 for wasm in &ctx.target_names {
354 let normalized_wasm = wasm.as_ref().replace('-', "_");
359 let import_name = format!("__wasip1_vfs_{normalized_wasm}__start");
360
361 module.renew_call_fn(
362 (UniqueName::NAMESPACE, &import_name).get_fid(&module.imports)?,
363 ctx.start_func_id.as_ref().unwrap()[wasm],
364 )?;
366 }
367
368 Ok(())
369 }
370}
371
372#[derive(Debug, Default)]
379pub struct MainVoidFunc {
380 synthesized_targets: HashSet<String>,
386}
387
388impl Generator for MainVoidFunc {
389 fn pre_target(
390 &mut self,
391 module: &mut walrus::Module,
392 _: &GeneratorCtx,
393 external: &ModuleExternal,
394 ) -> eyre::Result<()> {
395 let id = match "__main_void".get_fid(&module.exports).ok() {
396 Some(id) => id,
397 None => {
398 log::info!(
400 "No `__main_void` export found for target `{}`; synthesizing wrapper from `_start`.",
401 external.name
402 );
403
404 let renamed_start = UniqueName::SpecialFunc(
408 &SpecialFuncUniqueName::Start(&external.name),
409 )
410 .to_string();
411
412 let start_fid = renamed_start
413 .as_str()
414 .get_fid(&module.exports)
415 .or_else(|_| "_start".get_fid(&module.exports))
416 .wrap_err_with(|| {
417 eyre::eyre!(
418 "Target `{}` has neither `__main_void` nor `_start` export",
419 external.name
420 )
421 })?;
422
423 let wrapper = module
425 .add_func(&[], &[ValType::I32], |builder, _| {
426 builder.func_body().call(start_fid).i32_const(0);
427 Ok(())
428 })
429 .wrap_err("Failed to create synthetic __main_void wrapper")?;
430
431 module.exports.add("__main_void", wrapper);
432
433 self.synthesized_targets.insert(external.name.to_string());
434
435 wrapper
436 }
437 };
438
439 module
440 .exports
441 .get_mut(module.exports.get_exported_func(id).unwrap().id())
442 .name =
443 UniqueName::SpecialFunc(&SpecialFuncUniqueName::MainVoid(&external.name)).to_string();
444
445 Ok(())
446 }
447
448 fn post_combine(
449 &mut self,
450 module: &mut walrus::Module,
451 ctx: &GeneratorCtx,
452 ) -> eyre::Result<()> {
453 for wasm in &ctx.target_names {
454 if let Some(fid) = (
455 UniqueName::NAMESPACE,
456 &UniqueName::SpecialFunc(&SpecialFuncUniqueName::MainVoid(wasm)),
457 )
458 .get_fid(&module.imports)
459 .ok()
460 {
461 let main_void_func_name =
462 UniqueName::SpecialFunc(&SpecialFuncUniqueName::MainVoid(wasm)).to_string();
463
464 if self.synthesized_targets.contains(wasm.as_ref()) {
470 log::info!(
471 "Skipping main_void call-graph rewriting for synthesized target `{wasm}`."
472 );
473 module.connect_func_alt_with_remove_export(
474 fid,
475 main_void_func_name,
476 ctx.unstable_print_debug,
477 )?;
478 continue;
479 }
480
481 let main_void_func_id = main_void_func_name.get_fid(&module.exports)?;
482 let start_fn_id = ctx.start_func_id.as_ref().unwrap()[wasm];
483
484 let fake_fn_id = module.add_func(&[], &[walrus::ValType::I32], |func, _| {
485 func.func_body().i32_const(0).return_();
486
487 Ok(())
488 })?;
489
490 let call_main_void: i32 = module
491 .funcs
492 .rewrite(
493 |instr, _| {
494 if let walrus::ir::Instr::Call(c) = instr {
495 if c.func == main_void_func_id {
496 c.func = fake_fn_id;
497 1
498 } else {
499 0
500 }
501 } else {
502 0
503 }
504 },
505 start_fn_id,
506 )
507 .wrap_err("Failed to read main_void calls")?
508 .into_iter()
509 .sum();
510
511 if call_main_void == 0 {
512 let call_count = module
513 .funcs
514 .flat_read(
515 |instr, _| {
516 if let walrus::ir::Instr::Call(c) = instr {
517 if c.func == main_void_func_id { 1 } else { 0 }
518 } else {
519 0
520 }
521 },
522 start_fn_id,
523 )
524 .wrap_err("Failed to read main_void calls")?
525 .into_iter()
526 .count();
527
528 if call_count == 1 {
529 log::warn!(
530 "main_void is not called directly in start function, but called in nested function. we replaced once call to a fake function that returns 0."
531 );
532 } else {
533 if call_count > 1 {
534 log::warn!(
535 "main_void is not called directly in start function, and called in nested function. main_void called multiple times in start function, rust's default is once."
536 );
537 } else {
538 log::warn!(
539 "main_void is not called in nested start function, we think call_indirect is used. we replaced all calls to a fake function that returns 0."
540 );
541 module
545 .renew_call_fn(main_void_func_id, fake_fn_id)
546 .wrap_err("Failed to rewrite main_void call in start")?;
547 }
548 }
549 let start_fn_id =
550 module.nested_copy_func(start_fn_id, &[start_fn_id], true, true)?;
551 module
552 .funcs
553 .flat_rewrite(
554 |instr, _| {
555 if let walrus::ir::Instr::Call(c) = instr {
556 if c.func == main_void_func_id {
557 c.func = fake_fn_id;
558 }
559 }
560 },
561 start_fn_id,
562 false,
563 )
564 .wrap_err("Failed to read main_void calls")?;
565 } else if call_main_void > 1 {
566 log::warn!(
567 "main_void called multiple times in start function, rust's default is once. we replaced all calls to a fake function that returns 0."
568 );
569 }
570
571 module.connect_func_alt_with_remove_export(
572 fid,
573 main_void_func_name,
574 ctx.unstable_print_debug,
575 )?;
576 } else {
577 log::warn!(
578 "No main_void found for {wasm}. You can use {} directly",
579 UniqueName::SpecialFunc(&SpecialFuncUniqueName::MainVoid(wasm)).to_string()
580 );
581 }
582 }
583
584 Ok(())
585 }
586}
587