Skip to main content

wasi_virt_layer_cli/generator/
shared_global.rs

1use eyre::Context as _;
2use walrus::FunctionId;
3
4use crate::{
5    args::TargetMemoryType,
6    generator::{
7        Generator,
8    },
9    instrs::InstrRewrite as _,
10    unique_name::UniqueName,
11    util::{
12        WalrusFID as _, WalrusUtilExport, WalrusUtilFuncs as _, WalrusUtilImport as _,
13        WalrusUtilModule as _,
14    },
15};
16
17/// https://github.com/WebAssembly/binaryen/issues/7916
18/// 0: Failed to load Wasm file: ./dist\threads_vfs.core.opt.adjusted.wasm
19/// 1: failed to parse global section
20/// 2: malformed mutability -- or shared globals require the shared-everything-threads proposal (at offset 0x49f)
21///
22/// The Globals causing errors during memory expansion are those generated
23/// by wasm-opt --multi-memory-lowering,
24/// so for now we will only address these.
25/// When a newly created thread is executed,
26/// it will use the always-executable VFS code and memory,
27/// which are based on an address that never changes,
28/// and perform operations on them atomically.
29/// Operations on Global variables are replaced,
30/// and before memory unification,
31/// memory.grow is modified to be an atomic operation.
32/// Since this Global variable should only be modified internally,
33/// this approach should be sufficient.
34/// module
35///     .globals
36///     .iter()
37///     .map(|g| g.id())
38///     .collect::<Vec<_>>()
39///     .iter()
40///     .for_each(|g| {
41///         let g = module.globals.get_mut(*g);
42///         if let walrus::GlobalKind::Local(_) = g.kind {
43///             if g.mutable {
44///                 g.shared = true;
45///             }
46///         }
47///     });
48/// Generator responsible for managing globally shared variables to enable multi-threading atomic modifications.
49#[derive(Debug, Default)]
50pub struct SharedGlobal {
51    before_globals: Option<usize>,
52    before_memories: Option<usize>,
53}
54
55/// Enum containing identifiers for alternative shared global function replacements and locker usages.
56#[derive(Debug, strum::AsRefStr, strum::EnumCount, PartialEq, Eq, Hash)]
57#[strum(serialize_all = "snake_case")]
58pub enum SharedGlobalFnsName {
59    /// Wrapper replacing a global variable assignment internally without locking overhead.
60    GlobalAltSet,
61    GlobalAltSetWithLock,
62    /// Thread-safe wrapper evaluating and retrieving the global value.
63    GlobalAltGet,
64    /// Fast wrapper evaluating the global value bypassing thread synchronization lock operations.
65    GlobalAltGetNoWait,
66    /// Singleton wrapper assigning an initializing value solely on a one-time startup sequence.
67    GlobalAltInitOnce,
68    /// Utility function yielding the exact offset index memory location storing the global proxy.
69    GlobalAltPos,
70    /// Locking function instance controlling concurrent memory accesses for a specific table identified by index.
71    Locker(usize),
72    #[strum(serialize = "locker")]
73    /// Uniquely identified primary initial lock mechanism controlling baseline single-memory environments.
74    LockerBase,
75    #[strum(serialize = "alt")]
76    /// Replaced function logic hooking WebAssembly natively executed `memory.grow` allocation algorithms.
77    MemoryGrowAlt,
78}
79
80impl SharedGlobalFnsName {
81    /// Checks whether the provided string identifier maps to a locker operation, extracting its index.
82    pub fn check_locker(str: impl AsRef<str>) -> Option<SharedGlobalFnsName> {
83        let s = str.as_ref();
84        let prefix = crate::unique_name::fmt!(SharedGlobalFns; "{}", SharedGlobalFnsName::Locker(0).as_ref());
85        if s.starts_with(&prefix) && s.len() > prefix.len() {
86            let index_str = &s[prefix.len() + 1..];
87            if let Ok(index) = index_str.parse::<usize>() {
88                return Some(SharedGlobalFnsName::Locker(index));
89            }
90        }
91        None
92    }
93}
94
95impl SharedGlobal {
96    fn post_lower_memory_inner(
97        &self,
98        module: &mut walrus::Module,
99        ctx: &crate::generator::GeneratorCtx,
100    ) -> eyre::Result<()> {
101        use std::collections::{HashMap, HashSet};
102        use walrus::ir::*;
103
104        if !matches!(ctx.target_memory_type, TargetMemoryType::Single) {
105            unreachable!();
106        }
107
108        if !ctx.threads {
109            return Ok(());
110        }
111
112        let used_mem_id = module
113            .funcs
114            .all_read(
115                |instr, _| {
116                    if let Instr::MemoryGrow(MemoryGrow { memory, .. }) = instr {
117                        Some(*memory)
118                    } else {
119                        None
120                    }
121                },
122                &[] as &[walrus::FunctionId],
123            )?
124            .into_iter()
125            .filter_map(|v| v)
126            .collect::<HashSet<_>>();
127
128        let mut lockers = used_mem_id
129            .into_iter()
130            .map(|mem_id| {
131                Self::gen_custom_locker(module, mem_id, ctx.unstable_print_debug)
132                    .wrap_err("Failed to generate custom locker function")
133                    .map(|(locker_id, export_name)| (mem_id, (locker_id, export_name)))
134            })
135            .collect::<eyre::Result<HashMap<_, _>>>()?;
136
137        Self::remove_gen_custom_locker_base(module, ctx.unstable_print_debug)
138            .wrap_err("Failed to remove base locker function")?;
139
140        module.funcs.all_rewrite(
141            |instr, _| {
142                if let Instr::MemoryGrow(MemoryGrow { memory, .. }) = instr {
143                    *instr = Instr::Call(Call {
144                        func: lockers.get(memory).unwrap().to_owned().0,
145                    });
146                }
147            },
148            &lockers.values().map(|(v, _)| *v).collect::<Vec<_>>(),
149        )?;
150
151        let offset_globals = module
152            .globals
153            .iter()
154            .filter(|g| {
155                g.mutable
156                    && matches!(
157                        g.kind,
158                        walrus::GlobalKind::Local(walrus::ConstExpr::Value(
159                            walrus::ir::Value::I32(_)
160                        ))
161                    )
162            })
163            .map(|g| g.id())
164            .collect::<Vec<_>>();
165
166        // print all globals and their initial values
167        log::info!("All mutable i32 globals:");
168        for global_id in &offset_globals {
169            let global = module.globals.get(*global_id);
170            let init = match global.kind {
171                walrus::GlobalKind::Local(walrus::ConstExpr::Value(walrus::ir::Value::I32(value))) => 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        // フラグなどでちゃんとマッチングをとるべきだが、
180        // 順序が関係ないので今は成り立っている
181        // todo!();
182        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            // External Memory Managerのメモリサイズが0ならば、グローバルは生成されない。
188            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        // print all globals and their initial values
200        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(value))) => value,
205                _ => unreachable!(),
206            };
207            log::info!(" - {}: initial value = {}", target_name, init);
208        }
209
210        let intrrupt_fn = ctx.starts.init_offset_global.get_fid(&module.exports)?;
211
212        for (global_id, target_name) in global_mappings {
213            let global = module.globals.get(global_id);
214            let init = match global.kind {
215                walrus::GlobalKind::Local(walrus::ConstExpr::Value(walrus::ir::Value::I32(
216                    value,
217                ))) => value,
218                _ => unreachable!(),
219            };
220
221            let global_set_alt_without_lock = UniqueName::SharedGlobalFnsForTarget(
222                &SharedGlobalFnsName::GlobalAltSet,
223                target_name,
224            )
225            .get_fid(&module.exports)?;
226            let global_set_alt_with_lock = UniqueName::SharedGlobalFnsForTarget(
227                &SharedGlobalFnsName::GlobalAltSetWithLock,
228                target_name,
229            )
230            .get_fid(&module.exports)?;
231            let global_init_alt_without_lock_once = UniqueName::SharedGlobalFnsForTarget(
232                &SharedGlobalFnsName::GlobalAltInitOnce,
233                target_name,
234            )
235            .get_fid(&module.exports)?;
236            let global_get_alt_with_lock = UniqueName::SharedGlobalFnsForTarget(
237                &SharedGlobalFnsName::GlobalAltGet,
238                target_name,
239            )
240            .get_fid(&module.exports)?;
241            let global_get_alt_without_lock = UniqueName::SharedGlobalFnsForTarget(
242                &SharedGlobalFnsName::GlobalAltGetNoWait,
243                target_name,
244            )
245            .get_fid(&module.exports)?;
246            let global_alt_pos = UniqueName::SharedGlobalFnsForTarget(
247                &SharedGlobalFnsName::GlobalAltPos,
248                target_name,
249            )
250            .get_fid(&module.exports)?;
251
252            module
253                .exports
254                .erase_with(global_alt_pos, ctx.unstable_print_debug)?;
255
256            let start_local = module.funcs.get_mut(intrrupt_fn).kind.unwrap_local_mut();
257            start_local
258                .builder_mut()
259                .func_body()
260                .i32_const(init)
261                .call(global_init_alt_without_lock_once);
262
263            // The locker is locked at the point it is called. So we can replace
264            for (_, (locker_id, _)) in lockers.iter_mut() {
265                use walrus::ir::*;
266                let new_locker =
267                    module.nested_copy_func(*locker_id, &[] as &[FunctionId], true, true)?;
268
269                module.funcs.flat_rewrite(
270                    |instr, _| match instr {
271                        Instr::GlobalGet(GlobalGet { global }) if *global == global_id => {
272                            *instr = Instr::Call(Call {
273                                func: global_get_alt_without_lock,
274                            });
275                        }
276                        Instr::GlobalSet(GlobalSet { global }) if *global == global_id => {
277                            *instr = Instr::Call(Call {
278                                func: global_set_alt_without_lock,
279                            });
280                        }
281                        _ => {}
282                    },
283                    new_locker,
284                    true,
285                )?;
286
287                module.renew_call_fn(*locker_id, new_locker)?;
288                *locker_id = new_locker;
289            }
290
291            module
292                .funcs
293                .all_rewrite(
294                    |instr, _| match instr {
295                        walrus::ir::Instr::GlobalSet(walrus::ir::GlobalSet { global })
296                            if *global == global_id =>
297                        {
298                            // log::warn!(
299                            //     "Rewriting global set to nop for global {:?}",
300                            //     global_id,
301                            // );
302                            // *instr = walrus::ir::Instr::Drop(walrus::ir::Drop {});
303                            *instr = walrus::ir::Instr::Call(walrus::ir::Call {
304                                func: global_set_alt_with_lock,
305                            });
306                        }
307                        walrus::ir::Instr::GlobalGet(walrus::ir::GlobalGet { global })
308                            if *global == global_id =>
309                        {
310                            *instr = walrus::ir::Instr::Call(walrus::ir::Call {
311                                func: global_get_alt_with_lock,
312                            });
313                        }
314                        _ => {}
315                    },
316                    &lockers.values().map(|(v, _)| *v).collect::<Vec<_>>(),
317                )
318                .wrap_err("Failed to rewrite global set/get")?;
319
320            module.globals.delete(global_id);
321
322            module
323                .exports
324                .erase_with(global_set_alt_with_lock, ctx.unstable_print_debug)?;
325            module
326                .exports
327                .erase_with(global_set_alt_without_lock, ctx.unstable_print_debug)?;
328            module
329                .exports
330                .erase_with(global_init_alt_without_lock_once, ctx.unstable_print_debug)?;
331            module
332                .exports
333                .erase_with(global_get_alt_with_lock, ctx.unstable_print_debug)?;
334            module
335                .exports
336                .erase_with(global_get_alt_without_lock, ctx.unstable_print_debug)?;
337        }
338
339        for (_, (_, name)) in lockers {
340            module.exports.erase_with(&name, ctx.unstable_print_debug)?;
341        }
342
343        Ok(())
344    }
345}
346
347impl Generator for SharedGlobal {
348    fn post_combine(
349            &mut self,
350            module: &mut walrus::Module,
351            _: &super::GeneratorCtx,
352        ) -> eyre::Result<()> {
353        self.before_globals = Some(module.globals.iter()
354            .filter(|g| {
355                g.mutable
356                    && matches!(
357                        g.kind,
358                        walrus::GlobalKind::Local(walrus::ConstExpr::Value(
359                            walrus::ir::Value::I32(_)
360                        ))
361                    )
362            })
363            .count());
364
365        self.before_memories = Some(module.memories.iter().count());
366
367        Ok(())
368    }
369
370    fn post_lower_memory(
371        &mut self,
372        module: &mut walrus::Module,
373        ctx: &crate::generator::GeneratorCtx,
374    ) -> eyre::Result<()> {
375        if !matches!(ctx.target_memory_type, TargetMemoryType::Single) {
376            unreachable!();
377        }
378
379        if !ctx.threads {
380            return Ok(());
381        }
382
383        self.post_lower_memory_inner(module, ctx)?;
384
385        Ok(())
386    }
387}
388
389impl SharedGlobal {
390    #[allow(unused_variables)]
391    fn gen_custom_locker(
392        module: &mut walrus::Module,
393        mem_id: walrus::MemoryId,
394        is_debug: bool,
395    ) -> eyre::Result<(walrus::FunctionId, String)> {
396        let alt_id = (
397            "wasip1-vfs_single_memory",
398            &UniqueName::SharedGlobalFns(&SharedGlobalFnsName::MemoryGrowAlt),
399        )
400            .get_fid(&module.imports)?;
401
402        // print all exports
403        log::info!("Current exports:");
404        for export in module.exports.iter() {
405            log::info!(" - {}", export.name);
406        }
407
408        let base_locker = UniqueName::SharedGlobalFns(&SharedGlobalFnsName::LockerBase)
409            .get_fid(&module.exports)?;
410
411        let locker_id = module.copy_func(base_locker)?;
412
413        let export_name =
414            UniqueName::SharedGlobalFns(&SharedGlobalFnsName::Locker(mem_id.index())).to_string();
415        // todo!(); This is essential for it to function.
416        {
417            module.exports.add(&export_name, locker_id);
418        }
419
420        let locker = module.funcs.get_mut(locker_id);
421
422        use walrus::ir::*;
423
424        locker
425            .kind
426            .unwrap_local_mut()
427            .builder_mut()
428            .func_body()
429            .rewrite(|instr, _| {
430                if let Instr::Call(Call { func }) = instr {
431                    if *func == alt_id {
432                        *instr = Instr::MemoryGrow(MemoryGrow { memory: mem_id });
433                    }
434                }
435            })?;
436
437        Ok((locker_id, export_name))
438    }
439
440    fn remove_gen_custom_locker_base(module: &mut walrus::Module, debug: bool) -> eyre::Result<()> {
441        use walrus::ir::*;
442
443        let alt_id = (
444            "wasip1-vfs_single_memory",
445            &UniqueName::SharedGlobalFns(&SharedGlobalFnsName::MemoryGrowAlt),
446        )
447            .get_fid(&module.imports)?;
448        let base_locker = UniqueName::SharedGlobalFns(&SharedGlobalFnsName::LockerBase)
449            .get_fid(&module.exports)?;
450        if !debug {
451            module.funcs.delete(base_locker);
452            module.funcs.delete(alt_id);
453
454            module.exports.erase_with(base_locker, debug)?;
455        } else {
456            let mem_id = module.memories.iter().next().unwrap().id();
457
458            module
459                .funcs
460                .get_mut(base_locker)
461                .kind
462                .unwrap_local_mut()
463                .builder_mut()
464                .func_body()
465                .rewrite(|instr, _| {
466                    if let Instr::Call(Call { func }) = instr {
467                        if *func == alt_id {
468                            *instr = Instr::MemoryGrow(MemoryGrow { memory: mem_id });
469                        }
470                    }
471                })?;
472        }
473
474        module.imports.erase(alt_id)?;
475
476        Ok(())
477    }
478}