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(
69 mut self,
70 module: &mut walrus::Module,
71 threads: bool,
72 ) -> eyre::Result<Option<MemoryId>> {
73 let external_size = (0..=0x10000)
74 .find(|i| *i * 64 * 1024 >= self.external_size)
75 .ok_or_else(|| eyre::eyre!("Failed to find external size in 0..=0x10000"))?;
76
77 self.current_size += external_size;
78
79 let mem = module.memories.get_mut(self.mem_id);
80
81 mem.initial = self.current_size as u64;
82 mem.shared = threads;
83
84 if threads {
85 mem.maximum = Some(mem.initial);
86 }
87
88 if self.current_size == 0 {
89 module.memories.delete(self.mem_id);
91 return Ok(None);
92 }
93
94 Ok(Some(self.mem_id))
95 }
96}
97
98#[derive(Debug, Default)]
100pub struct ResetFunc;
101
102impl Generator for ResetFunc {
103 fn post_combine(
104 &mut self,
105 module: &mut walrus::Module,
106 ctx: &GeneratorCtx,
107 ) -> eyre::Result<()> {
108 let mut mem_manager = VFSExternalMemoryManager::new(module);
109
110 let initializers = module
111 .add_func(&[], &[], |_, _| Ok(()))
112 .wrap_err_with(|| eyre::eyre!("Failed to add initializer function"))?;
113
114 for wasm in &ctx.target_names {
115 let wasm_mem = ctx.target_used_memory_id.as_ref().unwrap()[wasm];
116 let starter = ctx.starts.flesh_target_start[wasm].get_fid(&module.exports)?;
117
118 if let Some(reset) = (
119 UniqueName::NAMESPACE,
120 &UniqueName::SpecialFunc(&SpecialFuncUniqueName::Reset(wasm)),
121 )
122 .get_fid(&module.imports)
123 .ok()
124 {
125 let global = ctx.target_used_global_id.as_ref().unwrap()[wasm]
126 .iter()
127 .copied()
128 .map(|g| module.globals.get(g))
129 .filter(|g| g.mutable)
130 .filter_map(|g| {
131 if let GlobalKind::Local(ConstExpr::Value(v)) = g.kind {
132 Some((g.id(), v.clone()))
133 } else {
134 log::warn!(
135 "Global segment {:?} is not a value, we support only local variables",
136 g.kind
137 );
138 None
139 }
140 })
141 .collect::<Box<_>>();
142
143 let data_range = module
144 .data
145 .iter()
146 .filter_map(|data| {
147 match &data.kind {
148 DataKind::Active { memory, offset } if *memory == wasm_mem => {
149 if let ConstExpr::Value(v) = offset {
150 if let ir::Value::I32(offset) = v {
151 Some((*offset, data.value.len()))
152 } else {
153 log::warn!(
154 "Data segment {:?} is not i32, we support only i32",
155 offset
156 );
157 None
158 }
159 } else {
160 log::warn!(
161 "Data segment {:?} is not a value, we support only i32",
162 offset
163 );
164 None
165 }
166 }
167 _ => None,
169 }
170 })
171 .collect::<Box<_>>();
172
173 let zero_range = std::iter::once(Some(0i32))
174 .chain(
175 data_range
176 .iter()
177 .flat_map(|(offset, len)| [Some(*offset), Some(*offset + *len as i32)]),
178 )
179 .chain(std::iter::once(None))
180 .collect::<Vec<_>>()
181 .chunks(2)
182 .map(|chunk| (chunk[0].unwrap(), chunk[1]))
183 .collect::<Box<_>>();
184
185 let mem_init = data_range
186 .into_iter()
187 .map(|(offset, len)| (offset, len, mem_manager.alloc(len)))
188 .collect::<Box<_>>();
189
190 let reset_area_mem_id = mem_manager.memory_id();
191
192 let resetter = module
193 .replace_imported_func(reset, |(builder, _)| {
194 let mut body = builder.func_body();
195
196 for (id, value) in global.iter() {
197 body.const_(*value).global_set(*id);
198 }
199 for (start, end) in zero_range.iter() {
200 body.i32_const(*start)
202 .i32_const(0);
204
205 if let Some(end) = end {
207 body.i32_const(*end - *start);
208 } else {
209 body.memory_size(wasm_mem);
210
211 body.i32_const(64 * 1024)
214 .binop(ir::BinaryOp::I32Mul)
215 .i32_const(*start)
216 .binop(ir::BinaryOp::I32Sub);
217 }
218 body.memory_fill(wasm_mem);
219 }
220 for (mem_offset, mem_len, mem_ptr) in mem_init.iter() {
221 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);
225 }
226
227 body.call(starter);
228 })
229 .to_eyre()
230 .wrap_err_with(|| eyre::eyre!("Failed to replace reset function for {wasm}"))?;
231
232 if ctx.unstable_print_debug {
233 module.exports.add(
234 &UniqueName::SpecialFunc(&SpecialFuncUniqueName::Resetter(wasm))
235 .to_string(),
236 resetter,
237 );
238 }
239
240 let mut func_body = module
241 .funcs
242 .get_mut(initializers)
243 .kind
244 .unwrap_local_mut()
245 .builder_mut()
246 .func_body();
247
248 for (offset, len, ptr) in mem_init {
249 func_body
250 .i32_const(ptr as i32) .i32_const(offset) .i32_const(len as i32) .memory_copy(wasm_mem, reset_area_mem_id);
254 }
255 }
256 }
257
258 let _ = mem_manager.flush(module, ctx.threads)?;
259
260 let init_id = if ctx.threads {
264 let reset_on_thread = UniqueName::SpecialFunc(&SpecialFuncUniqueName::ResetOnThread)
265 .get_fid(&module.exports)?;
266 let reset_on_thread_once = (
267 UniqueName::NAMESPACE,
268 &UniqueName::SpecialFunc(&SpecialFuncUniqueName::ResetOnThreadOnce),
269 )
270 .get_fid(&module.imports)?;
271
272 module
278 .replace_imported_func(reset_on_thread_once, |(builder, _)| {
279 builder.func_body().call(initializers);
280 })
281 .to_eyre()
282 .wrap_err("Failed to replace reset_on_thread_once import")?;
283
284 reset_on_thread
285 } else {
286 initializers
287 };
288
289 let save_target_memory = ctx.starts.save_target_memory.get_fid(&module.exports)?;
290
291 module
292 .funcs
293 .get_mut(save_target_memory)
294 .kind
295 .unwrap_local_mut()
296 .builder_mut()
297 .func_body()
298 .call(init_id);
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}