wasi_virt_layer_cli/generator/
special_func.rs1use eyre::Context as _;
2use walrus::*;
3
4use crate::{
5 generator::{Generator, GeneratorCtx, ModuleExternal},
6 instrs::InstrRewrite as _,
7 unique_name::UniqueName,
8 util::{ResultUtil as _, WalrusFID, WalrusUtilFuncs as _, WalrusUtilModule as _, WasmName},
9};
10
11#[derive(Debug, strum::AsRefStr, strum::EnumCount, Hash, PartialEq, Eq)]
13#[strum(serialize_all = "snake_case")]
14pub enum SpecialFuncUniqueName<'a> {
15 Resetter(&'a WasmName),
17 ResetOnThread,
19 ResetOnThreadOnce,
21 StartInitOld,
23 Start(&'a WasmName),
25 MainVoid(&'a WasmName),
27 Reset(&'a WasmName),
29}
30
31pub struct VFSExternalMemoryManager {
35 external_size: usize,
36 current_size: usize, mem_id: MemoryId,
38}
39
40impl VFSExternalMemoryManager {
41 pub fn new(module: &mut walrus::Module) -> Self {
43 let mem_id = module.memories.add_local(true, false, 0, None, None);
44
45 Self {
46 external_size: 0,
47 current_size: 0,
48 mem_id,
49 }
50 }
51
52 pub fn memory_id(&self) -> MemoryId {
54 self.mem_id
55 }
56
57 pub fn alloc(&mut self, size: usize) -> usize {
59 let ptr = self.current_size * 64 * 1024 + self.external_size;
60 self.external_size += size;
61
62 ptr
63 }
64
65 pub fn flush(mut self, module: &mut walrus::Module, threads: bool) -> eyre::Result<MemoryId> {
67 let external_size = (0..=0x10000)
68 .find(|i| *i * 64 * 1024 >= self.external_size)
69 .ok_or_else(|| eyre::eyre!("Failed to find external size in 0..=0x10000"))?;
70
71 self.current_size += external_size;
72
73 let mem = module.memories.get_mut(self.mem_id);
74
75 mem.initial = self.current_size as u64;
76 mem.shared = threads;
77
78 if threads {
79 mem.maximum = Some(mem.initial);
80 }
81
82 Ok(self.mem_id)
83 }
84}
85
86#[derive(Debug, Default)]
88pub struct ResetFunc;
89
90impl Generator for ResetFunc {
91 fn post_combine(
92 &mut self,
93 module: &mut walrus::Module,
94 ctx: &GeneratorCtx,
95 ) -> eyre::Result<()> {
96 let mut mem_manager = VFSExternalMemoryManager::new(module);
97
98 let initializers = module
99 .add_func(&[], &[], |_, _| Ok(()))
100 .wrap_err_with(|| eyre::eyre!("Failed to add initializer function"))?;
101
102 let tmp_start_section_id = module.add_func(&[], &[], |_, _| Ok(()))?;
103
104 for wasm in &ctx.target_names {
105 let wasm_mem = ctx.target_used_memory_id.as_ref().unwrap()[wasm];
106
107 if let Some(reset) = (
108 UniqueName::NAMESPACE,
109 &UniqueName::SpecialFunc(&SpecialFuncUniqueName::Reset(wasm)),
110 )
111 .get_fid(&module.imports)
112 .ok()
113 {
114 let global = ctx.target_used_global_id.as_ref().unwrap()[wasm]
115 .iter()
116 .copied()
117 .map(|g| module.globals.get(g))
118 .filter(|g| g.mutable)
119 .filter_map(|g| {
120 if let GlobalKind::Local(ConstExpr::Value(v)) = g.kind {
121 Some((g.id(), v.clone()))
122 } else {
123 log::warn!(
124 "Global segment {:?} is not a value, we support only local variables",
125 g.kind
126 );
127 None
128 }
129 })
130 .collect::<Box<_>>();
131
132 let data_range = module
133 .data
134 .iter()
135 .filter_map(|data| {
136 match &data.kind {
137 DataKind::Active { memory, offset } if *memory == wasm_mem => {
138 if let ConstExpr::Value(v) = offset {
139 if let ir::Value::I32(offset) = v {
140 Some((*offset, data.value.len()))
141 } else {
142 log::warn!(
143 "Data segment {:?} is not i32, we support only i32",
144 offset
145 );
146 None
147 }
148 } else {
149 log::warn!(
150 "Data segment {:?} is not a value, we support only i32",
151 offset
152 );
153 None
154 }
155 }
156 _ => None,
158 }
159 })
160 .collect::<Box<_>>();
161
162 let zero_range = std::iter::once(Some(0i32))
163 .chain(
164 data_range
165 .iter()
166 .flat_map(|(offset, len)| [Some(*offset), Some(*offset + *len as i32)]),
167 )
168 .chain(std::iter::once(None))
169 .collect::<Vec<_>>()
170 .chunks(2)
171 .map(|chunk| (chunk[0].unwrap(), chunk[1]))
172 .collect::<Box<_>>();
173
174 let mem_init = data_range
175 .into_iter()
176 .map(|(offset, len)| (offset, len, mem_manager.alloc(len)))
177 .collect::<Box<_>>();
178
179 let reset_area_mem_id = mem_manager.memory_id();
180
181 let resetter = module
182 .replace_imported_func(reset, |(builder, _)| {
183 let mut body = builder.func_body();
184
185 for (id, value) in global.iter() {
186 body.const_(*value).global_set(*id);
187 }
188 for (start, end) in zero_range.iter() {
189 body.i32_const(*start)
191 .i32_const(0);
193
194 if let Some(end) = end {
196 body.i32_const(*end - *start);
197 } else {
198 body.memory_size(wasm_mem);
199
200 body.i32_const(64 * 1024)
203 .binop(ir::BinaryOp::I32Mul)
204 .i32_const(*start)
205 .binop(ir::BinaryOp::I32Sub);
206 }
207 body.memory_fill(wasm_mem);
208 }
209 for (mem_offset, mem_len, mem_ptr) in mem_init.iter() {
210 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);
214 }
215
216 body.call(tmp_start_section_id);
217 })
218 .to_eyre()
219 .wrap_err_with(|| eyre::eyre!("Failed to replace reset function for {wasm}"))?;
220
221 if ctx.unstable_print_debug {
222 module.exports.add(
223 &UniqueName::SpecialFunc(&SpecialFuncUniqueName::Resetter(wasm))
224 .to_string(),
225 resetter,
226 );
227 }
228
229 let mut func_body = module
230 .funcs
231 .get_mut(initializers)
232 .kind
233 .unwrap_local_mut()
234 .builder_mut()
235 .func_body();
236
237 for (offset, len, ptr) in mem_init {
238 func_body
239 .i32_const(ptr as i32) .i32_const(offset) .i32_const(len as i32) .memory_copy(wasm_mem, reset_area_mem_id);
243 }
244 }
245 }
246
247 let _ = mem_manager.flush(module, ctx.threads)?;
248
249 let init_id = if ctx.threads {
253 let reset_on_thread = UniqueName::SpecialFunc(&SpecialFuncUniqueName::ResetOnThread)
254 .get_fid(&module.exports)?;
255 let reset_on_thread_once = (
256 UniqueName::NAMESPACE,
257 &UniqueName::SpecialFunc(&SpecialFuncUniqueName::ResetOnThreadOnce),
258 )
259 .get_fid(&module.imports)?;
260
261 module.renew_call_fn(reset_on_thread_once, initializers)?;
267
268 reset_on_thread
269 } else {
270 initializers
271 };
272
273 let old_start = module.start.clone();
274 let new_start = module
275 .add_func(&[], &[], |builder, _| {
276 let mut body = builder.func_body();
277 body.call(init_id); if let Some(old_start) = old_start {
279 body.call(old_start);
280 }
281 Ok(())
282 })
283 .wrap_err_with(|| eyre::eyre!("Failed to add new start function"))?;
284
285 module.start = Some(new_start);
286
287 module.renew_call_fn(tmp_start_section_id, new_start)?;
288
289 if let Some(start) = old_start {
290 if ctx.unstable_print_debug {
291 module.exports.add(
292 &UniqueName::SpecialFunc(&SpecialFuncUniqueName::StartInitOld).to_string(),
293 start,
294 );
295 }
296 }
297
298 module
305 .funcs
306 .iter_mut()
307 .map(|func| {
308 match &mut func.kind {
309 walrus::FunctionKind::Local(l) => {
310 l.builder_mut()
311 .func_body()
312 .retain(|instr, _| !instr.is_data_drop());
313 }
314 _ => {}
315 }
316 Ok(())
317 })
318 .collect::<eyre::Result<Vec<_>>>()?;
319
320 Ok(())
321 }
322}
323
324#[derive(Debug, Default)]
326pub struct StartFunc;
327
328impl Generator for StartFunc {
329 fn pre_target(
330 &mut self,
331 module: &mut walrus::Module,
332 _: &GeneratorCtx,
333 external: &ModuleExternal,
334 ) -> eyre::Result<()> {
335 let id = "_start".get_fid(&module.exports)?;
336
337 module
338 .exports
339 .get_mut(module.exports.get_exported_func(id).unwrap().id())
340 .name =
341 UniqueName::SpecialFunc(&SpecialFuncUniqueName::Start(&external.name)).to_string();
342
343 Ok(())
344 }
345
346 fn post_combine(
347 &mut self,
348 module: &mut walrus::Module,
349 ctx: &GeneratorCtx,
350 ) -> eyre::Result<()> {
351 for wasm in &ctx.target_names {
352 let normalized_wasm = wasm.as_ref().replace('-', "_");
357 let import_name = format!("__wasip1_vfs_{normalized_wasm}__start");
358
359 module.renew_call_fn(
360 (UniqueName::NAMESPACE, &import_name).get_fid(&module.imports)?,
361 ctx.start_func_id.as_ref().unwrap()[wasm],
362 )?;
364 }
365
366 Ok(())
367 }
368}
369
370#[derive(Debug, Default)]
372pub struct MainVoidFunc;
373
374impl Generator for MainVoidFunc {
375 fn pre_target(
376 &mut self,
377 module: &mut walrus::Module,
378 _: &GeneratorCtx,
379 external: &ModuleExternal,
380 ) -> eyre::Result<()> {
381 let id = "__main_void".get_fid(&module.exports)?;
382
383 module
384 .exports
385 .get_mut(module.exports.get_exported_func(id).unwrap().id())
386 .name =
387 UniqueName::SpecialFunc(&SpecialFuncUniqueName::MainVoid(&external.name)).to_string();
388
389 Ok(())
390 }
391
392 fn post_combine(
393 &mut self,
394 module: &mut walrus::Module,
395 ctx: &GeneratorCtx,
396 ) -> eyre::Result<()> {
397 for wasm in &ctx.target_names {
398 if let Some(fid) = (
399 UniqueName::NAMESPACE,
400 &UniqueName::SpecialFunc(&SpecialFuncUniqueName::MainVoid(wasm)),
401 )
402 .get_fid(&module.imports)
403 .ok()
404 {
405 let main_void_func_name =
406 UniqueName::SpecialFunc(&SpecialFuncUniqueName::MainVoid(wasm)).to_string();
407 let main_void_func_id = main_void_func_name.get_fid(&module.exports)?;
408 let start_fn_id = ctx.start_func_id.as_ref().unwrap()[wasm];
409
410 let fake_fn_id = module.add_func(&[], &[walrus::ValType::I32], |func, _| {
411 func.func_body().i32_const(0).return_();
412
413 Ok(())
414 })?;
415
416 let call_main_void: i32 = module
417 .funcs
418 .rewrite(
419 |instr, _| {
420 if let walrus::ir::Instr::Call(c) = instr {
421 if c.func == main_void_func_id {
422 c.func = fake_fn_id;
423 1
424 } else {
425 0
426 }
427 } else {
428 0
429 }
430 },
431 start_fn_id,
432 )
433 .wrap_err("Failed to read main_void calls")?
434 .into_iter()
435 .sum();
436
437 if call_main_void == 0 {
438 let call_count = module
439 .funcs
440 .flat_read(
441 |instr, _| {
442 if let walrus::ir::Instr::Call(c) = instr {
443 if c.func == main_void_func_id { 1 } else { 0 }
444 } else {
445 0
446 }
447 },
448 start_fn_id,
449 )
450 .wrap_err("Failed to read main_void calls")?
451 .into_iter()
452 .count();
453
454 if call_count == 1 {
455 log::warn!(
456 "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."
457 );
458 } else {
459 if call_count > 1 {
460 log::warn!(
461 "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."
462 );
463 } else {
464 log::warn!(
465 "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."
466 );
467 module
471 .renew_call_fn(main_void_func_id, fake_fn_id)
472 .wrap_err("Failed to rewrite main_void call in start")?;
473 }
474 }
475 let start_fn_id =
476 module.nested_copy_func(start_fn_id, &[start_fn_id], true, true)?;
477 module
478 .funcs
479 .flat_rewrite(
480 |instr, _| {
481 if let walrus::ir::Instr::Call(c) = instr {
482 if c.func == main_void_func_id {
483 c.func = fake_fn_id;
484 }
485 }
486 },
487 start_fn_id,
488 false,
489 )
490 .wrap_err("Failed to read main_void calls")?;
491 } else if call_main_void > 1 {
492 log::warn!(
493 "main_void called multiple times in start function, rust's default is once. we replaced all calls to a fake function that returns 0."
494 );
495 }
496
497 module.connect_func_alt_with_remove_export(
498 fid,
499 main_void_func_name,
500 ctx.unstable_print_debug,
501 )?;
502 } else {
503 log::warn!(
504 "No main_void found for {wasm}. You can use {} directly",
505 UniqueName::SpecialFunc(&SpecialFuncUniqueName::MainVoid(wasm)).to_string()
506 );
507 }
508 }
509
510 Ok(())
511 }
512}