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::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/// https://github.com/WebAssembly/binaryen/issues/7916
16/// 0: Failed to load Wasm file: ./dist\threads_vfs.core.opt.adjusted.wasm
17/// 1: failed to parse global section
18/// 2: malformed mutability -- or shared globals require the shared-everything-threads proposal (at offset 0x49f)
19///
20/// The Globals causing errors during memory expansion are those generated
21/// by wasm-opt --multi-memory-lowering,
22/// so for now we will only address these.
23/// When a newly created thread is executed,
24/// it will use the always-executable VFS code and memory,
25/// which are based on an address that never changes,
26/// and perform operations on them atomically.
27/// Operations on Global variables are replaced,
28/// and before memory unification,
29/// memory.grow is modified to be an atomic operation.
30/// Since this Global variable should only be modified internally,
31/// this approach should be sufficient.
32/// module
33///     .globals
34///     .iter()
35///     .map(|g| g.id())
36///     .collect::<Vec<_>>()
37///     .iter()
38///     .for_each(|g| {
39///         let g = module.globals.get_mut(*g);
40///         if let walrus::GlobalKind::Local(_) = g.kind {
41///             if g.mutable {
42///                 g.shared = true;
43///             }
44///         }
45///     });
46/// Generator responsible for managing globally shared variables to enable multi-threading atomic modifications.
47#[derive(Debug, Default)]
48pub struct SharedGlobal {
49    before_globals: Option<usize>,
50    before_memories: Option<usize>,
51}
52
53/// Enum containing identifiers for alternative shared global function replacements and locker usages.
54#[derive(Debug, strum::AsRefStr, strum::EnumCount, PartialEq, Eq, Hash)]
55#[strum(serialize_all = "snake_case")]
56pub enum SharedGlobalFnsName {
57    /// Wrapper replacing a global variable assignment internally without locking overhead.
58    GlobalAltSet,
59    GlobalAltSetWithLock,
60    /// Thread-safe wrapper evaluating and retrieving the global value.
61    GlobalAltGet,
62    /// Fast wrapper evaluating the global value bypassing thread synchronization lock operations.
63    GlobalAltGetNoWait,
64    /// Singleton wrapper assigning an initializing value solely on a one-time startup sequence.
65    GlobalAltInitOnce,
66    /// Utility function yielding the exact offset index memory location storing the global proxy.
67    GlobalAltPos,
68    /// Locking function instance controlling concurrent memory accesses for a specific table identified by index.
69    Locker(usize),
70    #[strum(serialize = "locker")]
71    /// Uniquely identified primary initial lock mechanism controlling baseline single-memory environments.
72    LockerBase,
73    #[strum(serialize = "alt")]
74    /// Replaced function logic hooking WebAssembly natively executed `memory.grow` allocation algorithms.
75    MemoryGrowAlt,
76}
77
78impl SharedGlobalFnsName {
79    /// Checks whether the provided string identifier maps to a locker operation, extracting its index.
80    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.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        // print all globals and their initial values
165        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        // フラグなどでちゃんとマッチングをとるべきだが、
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(
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            // The locker is locked at the point it is called. So we can replace
266            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.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                .all_rewrite(
296                    |instr, _| match instr {
297                        walrus::ir::Instr::GlobalSet(walrus::ir::GlobalSet { global })
298                            if *global == global_id =>
299                        {
300                            // log::warn!(
301                            //     "Rewriting global set to nop for global {:?}",
302                            //     global_id,
303                            // );
304                            // *instr = walrus::ir::Instr::Drop(walrus::ir::Drop {});
305                            *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        // print all exports
409        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        // todo!(); This is essential for it to function.
422        {
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}