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