wasi_virt_layer_cli/generator/
shared_global.rs1use eyre::Context as _;
2use walrus::FunctionId;
3
4use crate::{
5 args::TargetMemoryType,
6 generator::Generator,
7 instrs::InstrRewrite as _,
8 unique_name::UniqueName,
9 util::{
10 WalrusFID as _, WalrusUtilExport, WalrusUtilFuncs as _, WalrusUtilImport as _,
11 WalrusUtilModule as _,
12 },
13};
14
15#[derive(Debug, Default)]
48pub struct SharedGlobal {
49 before_globals: Option<usize>,
50 before_memories: Option<usize>,
51}
52
53#[derive(Debug, strum::AsRefStr, strum::EnumCount, PartialEq, Eq, Hash)]
55#[strum(serialize_all = "snake_case")]
56pub enum SharedGlobalFnsName {
57 GlobalAltSet,
59 GlobalAltSetWithLock,
60 GlobalAltGet,
62 GlobalAltGetNoWait,
64 GlobalAltInitOnce,
66 GlobalAltPos,
68 Locker(usize),
70 #[strum(serialize = "locker")]
71 LockerBase,
73 #[strum(serialize = "alt")]
74 MemoryGrowAlt,
76}
77
78impl SharedGlobalFnsName {
79 pub fn check_locker(str: impl AsRef<str>) -> Option<SharedGlobalFnsName> {
81 let s = str.as_ref();
82 let prefix = crate::unique_name::fmt!(SharedGlobalFns; "{}", SharedGlobalFnsName::Locker(0).as_ref());
83 if s.starts_with(&prefix) && s.len() > prefix.len() {
84 let index_str = &s[prefix.len() + 1..];
85 if let Ok(index) = index_str.parse::<usize>() {
86 return Some(SharedGlobalFnsName::Locker(index));
87 }
88 }
89 None
90 }
91}
92
93impl SharedGlobal {
94 fn post_lower_memory_inner(
95 &self,
96 module: &mut walrus::Module,
97 ctx: &crate::generator::GeneratorCtx,
98 ) -> eyre::Result<()> {
99 use std::collections::{HashMap, HashSet};
100 use walrus::ir::*;
101
102 if !matches!(ctx.target_memory_type, TargetMemoryType::Single) {
103 unreachable!();
104 }
105
106 if !ctx.threads {
107 return Ok(());
108 }
109
110 let used_mem_id = module
111 .funcs
112 .all_read(
113 |instr, _| {
114 if let Instr::MemoryGrow(MemoryGrow { memory, .. }) = instr {
115 Some(*memory)
116 } else {
117 None
118 }
119 },
120 &[] as &[walrus::FunctionId],
121 )?
122 .into_iter()
123 .filter_map(|v| v)
124 .collect::<HashSet<_>>();
125
126 let mut lockers = used_mem_id
127 .into_iter()
128 .map(|mem_id| {
129 Self::gen_custom_locker(module, mem_id, ctx.unstable_print_debug)
130 .wrap_err("Failed to generate custom locker function")
131 .map(|(locker_id, export_name)| (mem_id, (locker_id, export_name)))
132 })
133 .collect::<eyre::Result<HashMap<_, _>>>()?;
134
135 Self::remove_gen_custom_locker_base(module, ctx.unstable_print_debug)
136 .wrap_err("Failed to remove base locker function")?;
137
138 module.funcs.par_all_rewrite(
139 |instr, _| {
140 if let Instr::MemoryGrow(MemoryGrow { memory, .. }) = instr {
141 *instr = Instr::Call(Call {
142 func: lockers.get(memory).unwrap().to_owned().0,
143 });
144 }
145 },
146 &lockers.values().map(|(v, _)| *v).collect::<Vec<_>>(),
147 )?;
148
149 let offset_globals = module
150 .globals
151 .iter()
152 .filter(|g| {
153 g.mutable
154 && matches!(
155 g.kind,
156 walrus::GlobalKind::Local(walrus::ConstExpr::Value(
157 walrus::ir::Value::I32(_)
158 ))
159 )
160 })
161 .map(|g| g.id())
162 .collect::<Vec<_>>();
163
164 log::info!("All mutable i32 globals:");
166 for global_id in &offset_globals {
167 let global = module.globals.get(*global_id);
168 let init = match global.kind {
169 walrus::GlobalKind::Local(walrus::ConstExpr::Value(walrus::ir::Value::I32(
170 value,
171 ))) => value,
172 _ => unreachable!(),
173 };
174 log::info!(" - {:?}: initial value = {}", global_id, init);
175 }
176
177 let target_globals = &offset_globals[self.before_globals.unwrap() as usize..];
178
179 let mut global_mappings = Vec::new();
183 for (i, name) in ctx.target_names.iter().enumerate() {
184 global_mappings.push((target_globals[i], name.as_ref()));
185 }
186 if self.before_memories.unwrap() > ctx.target_names.len() {
187 if target_globals.len() == ctx.target_names.len() + 1 {
189 global_mappings.push((
190 target_globals[ctx.target_names.len()],
191 "vfs_external_memory_manager",
192 ));
193 }
194 } else {
195 log::warn!(
196 "The number of target globals exceeds the number of mutable i32 globals. This may lead to incorrect behavior. Please verify the target names and global variables."
197 );
198 }
199 log::info!("Globals to be replaced:");
201 for (global_id, target_name) in &global_mappings {
202 let global = module.globals.get(*global_id);
203 let init = match global.kind {
204 walrus::GlobalKind::Local(walrus::ConstExpr::Value(walrus::ir::Value::I32(
205 value,
206 ))) => value,
207 _ => unreachable!(),
208 };
209 log::info!(" - {}: initial value = {}", target_name, init);
210 }
211
212 let intrrupt_fn = ctx.starts.init_offset_global.get_fid(&module.exports)?;
213
214 for (global_id, target_name) in global_mappings {
215 let global = module.globals.get(global_id);
216 let init = match global.kind {
217 walrus::GlobalKind::Local(walrus::ConstExpr::Value(walrus::ir::Value::I32(
218 value,
219 ))) => value,
220 _ => unreachable!(),
221 };
222
223 let global_set_alt_without_lock = UniqueName::SharedGlobalFnsForTarget(
224 &SharedGlobalFnsName::GlobalAltSet,
225 target_name,
226 )
227 .get_fid(&module.exports)?;
228 let global_set_alt_with_lock = UniqueName::SharedGlobalFnsForTarget(
229 &SharedGlobalFnsName::GlobalAltSetWithLock,
230 target_name,
231 )
232 .get_fid(&module.exports)?;
233 let global_init_alt_without_lock_once = UniqueName::SharedGlobalFnsForTarget(
234 &SharedGlobalFnsName::GlobalAltInitOnce,
235 target_name,
236 )
237 .get_fid(&module.exports)?;
238 let global_get_alt_with_lock = UniqueName::SharedGlobalFnsForTarget(
239 &SharedGlobalFnsName::GlobalAltGet,
240 target_name,
241 )
242 .get_fid(&module.exports)?;
243 let global_get_alt_without_lock = UniqueName::SharedGlobalFnsForTarget(
244 &SharedGlobalFnsName::GlobalAltGetNoWait,
245 target_name,
246 )
247 .get_fid(&module.exports)?;
248 let global_alt_pos = UniqueName::SharedGlobalFnsForTarget(
249 &SharedGlobalFnsName::GlobalAltPos,
250 target_name,
251 )
252 .get_fid(&module.exports)?;
253
254 module
255 .exports
256 .erase_with(global_alt_pos, ctx.unstable_print_debug)?;
257
258 let start_local = module.funcs.get_mut(intrrupt_fn).kind.unwrap_local_mut();
259 start_local
260 .builder_mut()
261 .func_body()
262 .i32_const(init)
263 .call(global_init_alt_without_lock_once);
264
265 for (_, (locker_id, _)) in lockers.iter_mut() {
267 use walrus::ir::*;
268 let new_locker =
269 module.nested_copy_func(*locker_id, &[] as &[FunctionId], true, true)?;
270
271 module.funcs.par_flat_rewrite(
272 |instr, _| match instr {
273 Instr::GlobalGet(GlobalGet { global }) if *global == global_id => {
274 *instr = Instr::Call(Call {
275 func: global_get_alt_without_lock,
276 });
277 }
278 Instr::GlobalSet(GlobalSet { global }) if *global == global_id => {
279 *instr = Instr::Call(Call {
280 func: global_set_alt_without_lock,
281 });
282 }
283 _ => {}
284 },
285 new_locker,
286 true,
287 )?;
288
289 module.renew_call_fn(*locker_id, new_locker)?;
290 *locker_id = new_locker;
291 }
292
293 module
294 .funcs
295 .par_all_rewrite(
296 |instr, _| match instr {
297 walrus::ir::Instr::GlobalSet(walrus::ir::GlobalSet { global })
298 if *global == global_id =>
299 {
300 *instr = walrus::ir::Instr::Call(walrus::ir::Call {
306 func: global_set_alt_with_lock,
307 });
308 }
309 walrus::ir::Instr::GlobalGet(walrus::ir::GlobalGet { global })
310 if *global == global_id =>
311 {
312 *instr = walrus::ir::Instr::Call(walrus::ir::Call {
313 func: global_get_alt_with_lock,
314 });
315 }
316 _ => {}
317 },
318 &lockers.values().map(|(v, _)| *v).collect::<Vec<_>>(),
319 )
320 .wrap_err("Failed to rewrite global set/get")?;
321
322 module.globals.delete(global_id);
323
324 module
325 .exports
326 .erase_with(global_set_alt_with_lock, ctx.unstable_print_debug)?;
327 module
328 .exports
329 .erase_with(global_set_alt_without_lock, ctx.unstable_print_debug)?;
330 module
331 .exports
332 .erase_with(global_init_alt_without_lock_once, ctx.unstable_print_debug)?;
333 module
334 .exports
335 .erase_with(global_get_alt_with_lock, ctx.unstable_print_debug)?;
336 module
337 .exports
338 .erase_with(global_get_alt_without_lock, ctx.unstable_print_debug)?;
339 }
340
341 for (_, (_, name)) in lockers {
342 module.exports.erase_with(&name, ctx.unstable_print_debug)?;
343 }
344
345 Ok(())
346 }
347}
348
349impl Generator for SharedGlobal {
350 fn post_combine(
351 &mut self,
352 module: &mut walrus::Module,
353 _: &super::GeneratorCtx,
354 ) -> eyre::Result<()> {
355 self.before_globals = Some(
356 module
357 .globals
358 .iter()
359 .filter(|g| {
360 g.mutable
361 && matches!(
362 g.kind,
363 walrus::GlobalKind::Local(walrus::ConstExpr::Value(
364 walrus::ir::Value::I32(_)
365 ))
366 )
367 })
368 .count(),
369 );
370
371 self.before_memories = Some(module.memories.iter().count());
372
373 Ok(())
374 }
375
376 fn post_lower_memory(
377 &mut self,
378 module: &mut walrus::Module,
379 ctx: &crate::generator::GeneratorCtx,
380 ) -> eyre::Result<()> {
381 if !matches!(ctx.target_memory_type, TargetMemoryType::Single) {
382 unreachable!();
383 }
384
385 if !ctx.threads {
386 return Ok(());
387 }
388
389 self.post_lower_memory_inner(module, ctx)?;
390
391 Ok(())
392 }
393}
394
395impl SharedGlobal {
396 #[allow(unused_variables)]
397 fn gen_custom_locker(
398 module: &mut walrus::Module,
399 mem_id: walrus::MemoryId,
400 is_debug: bool,
401 ) -> eyre::Result<(walrus::FunctionId, String)> {
402 let alt_id = (
403 "wasip1-vfs_single_memory",
404 &UniqueName::SharedGlobalFns(&SharedGlobalFnsName::MemoryGrowAlt),
405 )
406 .get_fid(&module.imports)?;
407
408 log::info!("Current exports:");
410 for export in module.exports.iter() {
411 log::info!(" - {}", export.name);
412 }
413
414 let base_locker = UniqueName::SharedGlobalFns(&SharedGlobalFnsName::LockerBase)
415 .get_fid(&module.exports)?;
416
417 let locker_id = module.copy_func(base_locker)?;
418
419 let export_name =
420 UniqueName::SharedGlobalFns(&SharedGlobalFnsName::Locker(mem_id.index())).to_string();
421 {
423 module.exports.add(&export_name, locker_id);
424 }
425
426 let locker = module.funcs.get_mut(locker_id);
427
428 use walrus::ir::*;
429
430 locker
431 .kind
432 .unwrap_local_mut()
433 .builder_mut()
434 .func_body()
435 .rewrite(|instr, _| {
436 if let Instr::Call(Call { func }) = instr {
437 if *func == alt_id {
438 *instr = Instr::MemoryGrow(MemoryGrow { memory: mem_id });
439 }
440 }
441 })?;
442
443 Ok((locker_id, export_name))
444 }
445
446 fn remove_gen_custom_locker_base(module: &mut walrus::Module, debug: bool) -> eyre::Result<()> {
447 use walrus::ir::*;
448
449 let alt_id = (
450 "wasip1-vfs_single_memory",
451 &UniqueName::SharedGlobalFns(&SharedGlobalFnsName::MemoryGrowAlt),
452 )
453 .get_fid(&module.imports)?;
454 let base_locker = UniqueName::SharedGlobalFns(&SharedGlobalFnsName::LockerBase)
455 .get_fid(&module.exports)?;
456 if !debug {
457 module.funcs.delete(base_locker);
458 module.funcs.delete(alt_id);
459
460 module.exports.erase_with(base_locker, debug)?;
461 } else {
462 let mem_id = module.memories.iter().next().unwrap().id();
463
464 module
465 .funcs
466 .get_mut(base_locker)
467 .kind
468 .unwrap_local_mut()
469 .builder_mut()
470 .func_body()
471 .rewrite(|instr, _| {
472 if let Instr::Call(Call { func }) = instr {
473 if *func == alt_id {
474 *instr = Instr::MemoryGrow(MemoryGrow { memory: mem_id });
475 }
476 }
477 })?;
478 }
479
480 module.imports.erase(alt_id)?;
481
482 Ok(())
483 }
484}