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<Option<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 if self.current_size == 0 {
85 module.memories.delete(self.mem_id);
87 return Ok(None);
88 }
89
90 Ok(Some(self.mem_id))
91 }
92}
93
94#[derive(Debug, Default)]
96pub struct ResetFunc;
97
98impl Generator for ResetFunc {
99 fn post_combine(
100 &mut self,
101 module: &mut walrus::Module,
102 ctx: &GeneratorCtx,
103 ) -> eyre::Result<()> {
104 let mut mem_manager = VFSExternalMemoryManager::new(module);
105
106 let initializers = module
107 .add_func(&[], &[], |_, _| Ok(()))
108 .wrap_err_with(|| eyre::eyre!("Failed to add initializer function"))?;
109
110 for wasm in &ctx.target_names {
111 let wasm_mem = ctx.target_used_memory_id.as_ref().unwrap()[wasm];
112 let starter = ctx.starts.flesh_target_start[wasm].get_fid(&module.exports)?;
113
114 if let Some(reset) = (
115 UniqueName::NAMESPACE,
116 &UniqueName::SpecialFunc(&SpecialFuncUniqueName::Reset(wasm)),
117 )
118 .get_fid(&module.imports)
119 .ok()
120 {
121 let global = ctx.target_used_global_id.as_ref().unwrap()[wasm]
122 .iter()
123 .copied()
124 .map(|g| module.globals.get(g))
125 .filter(|g| g.mutable)
126 .filter_map(|g| {
127 if let GlobalKind::Local(ConstExpr::Value(v)) = g.kind {
128 Some((g.id(), v.clone()))
129 } else {
130 log::warn!(
131 "Global segment {:?} is not a value, we support only local variables",
132 g.kind
133 );
134 None
135 }
136 })
137 .collect::<Box<_>>();
138
139 let data_range = module
140 .data
141 .iter()
142 .filter_map(|data| {
143 match &data.kind {
144 DataKind::Active { memory, offset } if *memory == wasm_mem => {
145 if let ConstExpr::Value(v) = offset {
146 if let ir::Value::I32(offset) = v {
147 Some((*offset, data.value.len()))
148 } else {
149 log::warn!(
150 "Data segment {:?} is not i32, we support only i32",
151 offset
152 );
153 None
154 }
155 } else {
156 log::warn!(
157 "Data segment {:?} is not a value, we support only i32",
158 offset
159 );
160 None
161 }
162 }
163 _ => None,
165 }
166 })
167 .collect::<Box<_>>();
168
169 let zero_range = std::iter::once(Some(0i32))
170 .chain(
171 data_range
172 .iter()
173 .flat_map(|(offset, len)| [Some(*offset), Some(*offset + *len as i32)]),
174 )
175 .chain(std::iter::once(None))
176 .collect::<Vec<_>>()
177 .chunks(2)
178 .map(|chunk| (chunk[0].unwrap(), chunk[1]))
179 .collect::<Box<_>>();
180
181 let mem_init = data_range
182 .into_iter()
183 .map(|(offset, len)| (offset, len, mem_manager.alloc(len)))
184 .collect::<Box<_>>();
185
186 let reset_area_mem_id = mem_manager.memory_id();
187
188 let resetter = module
189 .replace_imported_func(reset, |(builder, _)| {
190 let mut body = builder.func_body();
191
192 for (id, value) in global.iter() {
193 body.const_(*value).global_set(*id);
194 }
195 for (start, end) in zero_range.iter() {
196 body.i32_const(*start)
198 .i32_const(0);
200
201 if let Some(end) = end {
203 body.i32_const(*end - *start);
204 } else {
205 body.memory_size(wasm_mem);
206
207 body.i32_const(64 * 1024)
210 .binop(ir::BinaryOp::I32Mul)
211 .i32_const(*start)
212 .binop(ir::BinaryOp::I32Sub);
213 }
214 body.memory_fill(wasm_mem);
215 }
216 for (mem_offset, mem_len, mem_ptr) in mem_init.iter() {
217 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);
221 }
222
223 body.call(starter);
224 })
225 .to_eyre()
226 .wrap_err_with(|| eyre::eyre!("Failed to replace reset function for {wasm}"))?;
227
228 if ctx.unstable_print_debug {
229 module.exports.add(
230 &UniqueName::SpecialFunc(&SpecialFuncUniqueName::Resetter(wasm))
231 .to_string(),
232 resetter,
233 );
234 }
235
236 let mut func_body = module
237 .funcs
238 .get_mut(initializers)
239 .kind
240 .unwrap_local_mut()
241 .builder_mut()
242 .func_body();
243
244 for (offset, len, ptr) in mem_init {
245 func_body
246 .i32_const(ptr as i32) .i32_const(offset) .i32_const(len as i32) .memory_copy(wasm_mem, reset_area_mem_id);
250 }
251 }
252 }
253
254 let _ = mem_manager.flush(module, ctx.threads)?;
255
256 let init_id = if ctx.threads {
260 let reset_on_thread = UniqueName::SpecialFunc(&SpecialFuncUniqueName::ResetOnThread)
261 .get_fid(&module.exports)?;
262 let reset_on_thread_once = (
263 UniqueName::NAMESPACE,
264 &UniqueName::SpecialFunc(&SpecialFuncUniqueName::ResetOnThreadOnce),
265 )
266 .get_fid(&module.imports)?;
267
268 module.replace_imported_func(reset_on_thread_once, |(builder, _)| {
274 builder.func_body().call(initializers);
275 }).to_eyre().wrap_err("Failed to replace reset_on_thread_once import")?;
276
277 reset_on_thread
278 } else {
279 initializers
280 };
281
282 let save_target_memory = ctx.starts.save_target_memory.get_fid(&module.exports)?;
283
284 module
285 .funcs.get_mut(save_target_memory)
286 .kind
287 .unwrap_local_mut()
288 .builder_mut()
289 .func_body()
290 .call(init_id);
291
292 module
299 .funcs
300 .iter_mut()
301 .map(|func| {
302 match &mut func.kind {
303 walrus::FunctionKind::Local(l) => {
304 l.builder_mut()
305 .func_body()
306 .retain(|instr, _| !instr.is_data_drop());
307 }
308 _ => {}
309 }
310 Ok(())
311 })
312 .collect::<eyre::Result<Vec<_>>>()?;
313
314 Ok(())
315 }
316}
317
318#[derive(Debug, Default)]
320pub struct StartFunc;
321
322impl Generator for StartFunc {
323 fn pre_target(
324 &mut self,
325 module: &mut walrus::Module,
326 _: &GeneratorCtx,
327 external: &ModuleExternal,
328 ) -> eyre::Result<()> {
329 let id = "_start".get_fid(&module.exports)?;
330
331 module
332 .exports
333 .get_mut(module.exports.get_exported_func(id).unwrap().id())
334 .name =
335 UniqueName::SpecialFunc(&SpecialFuncUniqueName::Start(&external.name)).to_string();
336
337 Ok(())
338 }
339
340 fn post_combine(
341 &mut self,
342 module: &mut walrus::Module,
343 ctx: &GeneratorCtx,
344 ) -> eyre::Result<()> {
345 for wasm in &ctx.target_names {
346 let normalized_wasm = wasm.as_ref().replace('-', "_");
351 let import_name = format!("__wasip1_vfs_{normalized_wasm}__start");
352
353 module.renew_call_fn(
354 (UniqueName::NAMESPACE, &import_name).get_fid(&module.imports)?,
355 ctx.start_func_id.as_ref().unwrap()[wasm],
356 )?;
358 }
359
360 Ok(())
361 }
362}
363
364#[derive(Debug, Default)]
371pub struct MainVoidFunc {
372 synthesized_targets: HashSet<String>,
378}
379
380impl Generator for MainVoidFunc {
381 fn pre_target(
382 &mut self,
383 module: &mut walrus::Module,
384 _: &GeneratorCtx,
385 external: &ModuleExternal,
386 ) -> eyre::Result<()> {
387 let id = match "__main_void".get_fid(&module.exports).ok() {
388 Some(id) => id,
389 None => {
390 log::info!(
392 "No `__main_void` export found for target `{}`; synthesizing wrapper from `_start`.",
393 external.name
394 );
395
396 let renamed_start =
400 UniqueName::SpecialFunc(&SpecialFuncUniqueName::Start(&external.name))
401 .to_string();
402
403 let start_fid = renamed_start
404 .as_str()
405 .get_fid(&module.exports)
406 .or_else(|_| "_start".get_fid(&module.exports))
407 .wrap_err_with(|| {
408 eyre::eyre!(
409 "Target `{}` has neither `__main_void` nor `_start` export",
410 external.name
411 )
412 })?;
413
414 let wrapper = module
416 .add_func(&[], &[ValType::I32], |builder, _| {
417 builder.func_body().call(start_fid).i32_const(0);
418 Ok(())
419 })
420 .wrap_err("Failed to create synthetic __main_void wrapper")?;
421
422 module.exports.add("__main_void", wrapper);
423
424 self.synthesized_targets.insert(external.name.to_string());
425
426 wrapper
427 }
428 };
429
430 module
431 .exports
432 .get_mut(module.exports.get_exported_func(id).unwrap().id())
433 .name =
434 UniqueName::SpecialFunc(&SpecialFuncUniqueName::MainVoid(&external.name)).to_string();
435
436 Ok(())
437 }
438
439 fn post_combine(
440 &mut self,
441 module: &mut walrus::Module,
442 ctx: &GeneratorCtx,
443 ) -> eyre::Result<()> {
444 for wasm in &ctx.target_names {
445 if let Some(fid) = (
446 UniqueName::NAMESPACE,
447 &UniqueName::SpecialFunc(&SpecialFuncUniqueName::MainVoid(wasm)),
448 )
449 .get_fid(&module.imports)
450 .ok()
451 {
452 let main_void_func_name =
453 UniqueName::SpecialFunc(&SpecialFuncUniqueName::MainVoid(wasm)).to_string();
454
455 if self.synthesized_targets.contains(wasm.as_ref()) {
461 log::info!(
462 "Skipping main_void call-graph rewriting for synthesized target `{wasm}`."
463 );
464 module.connect_func_alt_with_remove_export(
465 fid,
466 main_void_func_name,
467 ctx.unstable_print_debug,
468 )?;
469 continue;
470 }
471
472 let main_void_func_id = main_void_func_name.get_fid(&module.exports)?;
473 let start_fn_id = ctx.start_func_id.as_ref().unwrap()[wasm];
474
475 let fake_fn_id = module.add_func(&[], &[walrus::ValType::I32], |func, _| {
476 func.func_body().i32_const(0).return_();
477
478 Ok(())
479 })?;
480
481 let call_main_void: i32 = module
482 .funcs
483 .rewrite(
484 |instr, _| {
485 if let walrus::ir::Instr::Call(c) = instr {
486 if c.func == main_void_func_id {
487 c.func = fake_fn_id;
488 1
489 } else {
490 0
491 }
492 } else {
493 0
494 }
495 },
496 start_fn_id,
497 )
498 .wrap_err("Failed to read main_void calls")?
499 .into_iter()
500 .sum();
501
502 if call_main_void == 0 {
503 let call_count = module
504 .funcs
505 .flat_read(
506 |instr, _| {
507 if let walrus::ir::Instr::Call(c) = instr {
508 if c.func == main_void_func_id { 1 } else { 0 }
509 } else {
510 0
511 }
512 },
513 start_fn_id,
514 )
515 .wrap_err("Failed to read main_void calls")?
516 .into_iter()
517 .count();
518
519 if call_count == 1 {
520 log::warn!(
521 "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."
522 );
523 } else {
524 if call_count > 1 {
525 log::warn!(
526 "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."
527 );
528 } else {
529 log::warn!(
530 "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."
531 );
532 module
536 .renew_call_fn(main_void_func_id, fake_fn_id)
537 .wrap_err("Failed to rewrite main_void call in start")?;
538 }
539 }
540 let start_fn_id =
541 module.nested_copy_func(start_fn_id, &[start_fn_id], true, true)?;
542 module
543 .funcs
544 .flat_rewrite(
545 |instr, _| {
546 if let walrus::ir::Instr::Call(c) = instr {
547 if c.func == main_void_func_id {
548 c.func = fake_fn_id;
549 }
550 }
551 },
552 start_fn_id,
553 false,
554 )
555 .wrap_err("Failed to read main_void calls")?;
556 } else if call_main_void > 1 {
557 log::warn!(
558 "main_void called multiple times in start function, rust's default is once. we replaced all calls to a fake function that returns 0."
559 );
560 }
561
562 module.connect_func_alt_with_remove_export(
563 fid,
564 main_void_func_name,
565 ctx.unstable_print_debug,
566 )?;
567 } else {
568 log::warn!(
569 "No main_void found for {wasm}. You can use {} directly",
570 UniqueName::SpecialFunc(&SpecialFuncUniqueName::MainVoid(wasm)).to_string()
571 );
572 }
573 }
574
575 Ok(())
576 }
577}