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 =
408 UniqueName::SpecialFunc(&SpecialFuncUniqueName::Start(&external.name))
409 .to_string();
410
411 let start_fid = renamed_start
412 .as_str()
413 .get_fid(&module.exports)
414 .or_else(|_| "_start".get_fid(&module.exports))
415 .wrap_err_with(|| {
416 eyre::eyre!(
417 "Target `{}` has neither `__main_void` nor `_start` export",
418 external.name
419 )
420 })?;
421
422 let wrapper = module
424 .add_func(&[], &[ValType::I32], |builder, _| {
425 builder.func_body().call(start_fid).i32_const(0);
426 Ok(())
427 })
428 .wrap_err("Failed to create synthetic __main_void wrapper")?;
429
430 module.exports.add("__main_void", wrapper);
431
432 self.synthesized_targets.insert(external.name.to_string());
433
434 wrapper
435 }
436 };
437
438 module
439 .exports
440 .get_mut(module.exports.get_exported_func(id).unwrap().id())
441 .name =
442 UniqueName::SpecialFunc(&SpecialFuncUniqueName::MainVoid(&external.name)).to_string();
443
444 Ok(())
445 }
446
447 fn post_combine(
448 &mut self,
449 module: &mut walrus::Module,
450 ctx: &GeneratorCtx,
451 ) -> eyre::Result<()> {
452 for wasm in &ctx.target_names {
453 if let Some(fid) = (
454 UniqueName::NAMESPACE,
455 &UniqueName::SpecialFunc(&SpecialFuncUniqueName::MainVoid(wasm)),
456 )
457 .get_fid(&module.imports)
458 .ok()
459 {
460 let main_void_func_name =
461 UniqueName::SpecialFunc(&SpecialFuncUniqueName::MainVoid(wasm)).to_string();
462
463 if self.synthesized_targets.contains(wasm.as_ref()) {
469 log::info!(
470 "Skipping main_void call-graph rewriting for synthesized target `{wasm}`."
471 );
472 module.connect_func_alt_with_remove_export(
473 fid,
474 main_void_func_name,
475 ctx.unstable_print_debug,
476 )?;
477 continue;
478 }
479
480 let main_void_func_id = main_void_func_name.get_fid(&module.exports)?;
481 let start_fn_id = ctx.start_func_id.as_ref().unwrap()[wasm];
482
483 let fake_fn_id = module.add_func(&[], &[walrus::ValType::I32], |func, _| {
484 func.func_body().i32_const(0).return_();
485
486 Ok(())
487 })?;
488
489 let call_main_void: i32 = module
490 .funcs
491 .rewrite(
492 |instr, _| {
493 if let walrus::ir::Instr::Call(c) = instr {
494 if c.func == main_void_func_id {
495 c.func = fake_fn_id;
496 1
497 } else {
498 0
499 }
500 } else {
501 0
502 }
503 },
504 start_fn_id,
505 )
506 .wrap_err("Failed to read main_void calls")?
507 .into_iter()
508 .sum();
509
510 if call_main_void == 0 {
511 let call_count = module
512 .funcs
513 .flat_read(
514 |instr, _| {
515 if let walrus::ir::Instr::Call(c) = instr {
516 if c.func == main_void_func_id { 1 } else { 0 }
517 } else {
518 0
519 }
520 },
521 start_fn_id,
522 )
523 .wrap_err("Failed to read main_void calls")?
524 .into_iter()
525 .count();
526
527 if call_count == 1 {
528 log::warn!(
529 "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."
530 );
531 } else {
532 if call_count > 1 {
533 log::warn!(
534 "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."
535 );
536 } else {
537 log::warn!(
538 "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."
539 );
540 module
544 .renew_call_fn(main_void_func_id, fake_fn_id)
545 .wrap_err("Failed to rewrite main_void call in start")?;
546 }
547 }
548 let start_fn_id =
549 module.nested_copy_func(start_fn_id, &[start_fn_id], true, true)?;
550 module
551 .funcs
552 .flat_rewrite(
553 |instr, _| {
554 if let walrus::ir::Instr::Call(c) = instr {
555 if c.func == main_void_func_id {
556 c.func = fake_fn_id;
557 }
558 }
559 },
560 start_fn_id,
561 false,
562 )
563 .wrap_err("Failed to read main_void calls")?;
564 } else if call_main_void > 1 {
565 log::warn!(
566 "main_void called multiple times in start function, rust's default is once. we replaced all calls to a fake function that returns 0."
567 );
568 }
569
570 module.connect_func_alt_with_remove_export(
571 fid,
572 main_void_func_name,
573 ctx.unstable_print_debug,
574 )?;
575 } else {
576 log::warn!(
577 "No main_void found for {wasm}. You can use {} directly",
578 UniqueName::SpecialFunc(&SpecialFuncUniqueName::MainVoid(wasm)).to_string()
579 );
580 }
581 }
582
583 Ok(())
584 }
585}