Skip to main content

wasi_virt_layer_cli/generator/
shared_global.rs

1use 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/// https://github.com/WebAssembly/binaryen/issues/7916
19/// 0: Failed to load Wasm file: ./dist\threads_vfs.core.opt.adjusted.wasm
20/// 1: failed to parse global section
21/// 2: malformed mutability -- or shared globals require the shared-everything-threads proposal (at offset 0x49f)
22///
23/// The Globals causing errors during memory expansion are those generated
24/// by wasm-opt --multi-memory-lowering,
25/// so for now we will only address these.
26/// When a newly created thread is executed,
27/// it will use the always-executable VFS code and memory,
28/// which are based on an address that never changes,
29/// and perform operations on them atomically.
30/// Operations on Global variables are replaced,
31/// and before memory unification,
32/// memory.grow is modified to be an atomic operation.
33/// Since this Global variable should only be modified internally,
34/// this approach should be sufficient.
35/// module
36///     .globals
37///     .iter()
38///     .map(|g| g.id())
39///     .collect::<Vec<_>>()
40///     .iter()
41///     .for_each(|g| {
42///         let g = module.globals.get_mut(*g);
43///         if let walrus::GlobalKind::Local(_) = g.kind {
44///             if g.mutable {
45///                 g.shared = true;
46///             }
47///         }
48///     });
49/// Generator responsible for managing globally shared variables to enable multi-threading atomic modifications.
50#[derive(Debug, Default)]
51pub struct SharedGlobal;
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    /// Thread-safe wrapper evaluating and retrieving the global value.
60    GlobalAltGet,
61    /// Fast wrapper evaluating the global value bypassing thread synchronization lock operations.
62    GlobalAltGetNoWait,
63    /// Singleton wrapper assigning an initializing value solely on a one-time startup sequence.
64    GlobalAltInitOnce,
65    /// Utility function yielding the exact offset index memory location storing the global proxy.
66    GlobalAltPos,
67    /// Locking function instance controlling concurrent memory accesses for a specific table identified by index.
68    Locker(usize),
69    #[strum(serialize = "locker")]
70    /// Uniquely identified primary initial lock mechanism controlling baseline single-memory environments.
71    LockerBase,
72    #[strum(serialize = "alt")]
73    /// Replaced function logic hooking WebAssembly natively executed `memory.grow` allocation algorithms.
74    MemoryGrowAlt,
75}
76
77impl SharedGlobalFnsName {
78    /// Checks whether the provided string identifier maps to a locker operation, extracting its index.
79    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 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 global_set_alt_without_lock =
148            UniqueName::SharedGlobalFns(&SharedGlobalFnsName::GlobalAltSet)
149                .get_fid(&module.exports)?;
150        let global_init_alt_without_lock_once =
151            UniqueName::SharedGlobalFns(&SharedGlobalFnsName::GlobalAltInitOnce)
152                .get_fid(&module.exports)?;
153        let global_get_alt_with_lock =
154            UniqueName::SharedGlobalFns(&SharedGlobalFnsName::GlobalAltGet)
155                .get_fid(&module.exports)?;
156        let global_get_alt_without_lock =
157            UniqueName::SharedGlobalFns(&SharedGlobalFnsName::GlobalAltGetNoWait)
158                .get_fid(&module.exports)?;
159
160        let global = module
161            .globals
162            .iter()
163            .last()
164            .map(|g| g)
165            .wrap_err_with(|| eyre::eyre!("Failed to get global ID"))?;
166
167        let init = match global.kind {
168            walrus::GlobalKind::Local(walrus::ConstExpr::Value(walrus::ir::Value::I32(value))) => {
169                value
170            }
171            _ => unreachable!(),
172        };
173
174        let global_id = global.id();
175
176        // Obtain the location within memory.
177        let global_alt_pos = UniqueName::SharedGlobalFns(&SharedGlobalFnsName::GlobalAltPos)
178            .get_fid(&module.exports)?;
179        // let global_alt_pos = module.funcs.get(global_alt_pos).kind.unwrap_local();
180        // let global_alt_pos = if let walrus::ir::Instr::Const(walrus::ir::Const {
181        //     value: walrus::ir::Value::I32(value),
182        // }) = global_alt_pos
183        //     .block(global_alt_pos.entry_block())
184        //     .instrs
185        //     .first()
186        //     .unwrap()
187        //     .0
188        // {
189        //     value
190        // } else {
191        //     unreachable!()
192        // };
193        module
194            .exports
195            .erase_with(global_alt_pos, ctx.unstable_print_debug)?;
196
197        // check global set in start section function
198        let start_id = if let Some(id) = module.start {
199            module
200                .nested_copy_func(id, &[id], false, false)
201                .wrap_err("Failed to create start function copy")?
202        } else {
203            // create a new start function
204            module.add_func(&[], &[], |_, _| Ok(()))?
205        };
206        module.start = Some(start_id);
207
208        if 0usize
209            < module
210                .funcs
211                .flat_rewrite(
212                    |instr, _| match instr {
213                        walrus::ir::Instr::GlobalSet(walrus::ir::GlobalSet { global })
214                            if *global == global_id =>
215                        {
216                            1usize
217                        }
218                        walrus::ir::Instr::GlobalGet(walrus::ir::GlobalGet { global })
219                            if *global == global_id =>
220                        {
221                            *instr = walrus::ir::Instr::Const(walrus::ir::Const {
222                                value: walrus::ir::Value::I32(init),
223                            });
224                            // println!("Rewrote global get to const i32 {init}");
225                            0usize
226                        }
227                        _ => 0usize,
228                    },
229                    start_id,
230                    false,
231                )?
232                .into_iter()
233                .sum()
234        {
235            eyre::bail!(
236                "The start section already contains a global set instruction. \
237                Please remove it manually and try again."
238            );
239        }
240
241        let start_local = module.funcs.get_mut(start_id).kind.unwrap_local_mut();
242        start_local
243            .builder_mut()
244            .func_body()
245            .i32_const(init)
246            .call(global_init_alt_without_lock_once);
247
248        // The locker is locked at the point it is called. So we can replace
249        for (_, (locker_id, name)) in lockers {
250            // println!("Rewriting locker: {:?}", locker_id);
251            use walrus::ir::*;
252            let new_locker =
253                // module.nested_copy_func(locker_id, &[] as &[FunctionId], false, false)?;
254                module.nested_copy_func(locker_id, &[] as &[FunctionId], true, true)?;
255
256            module.funcs.flat_rewrite(
257                |instr, _| match instr {
258                    Instr::GlobalGet(GlobalGet { global }) if *global == global_id => {
259                        *instr = Instr::Call(Call {
260                            func: global_get_alt_without_lock,
261                        });
262                    }
263                    _ => {}
264                },
265                new_locker,
266                true,
267            )?;
268
269            module.renew_call_fn(locker_id, new_locker)?;
270
271            module.exports.erase_with(&name, ctx.unstable_print_debug)?;
272        }
273
274        module
275            .funcs
276            .all_rewrite(
277                |instr, _| match instr {
278                    walrus::ir::Instr::GlobalSet(walrus::ir::GlobalSet { global })
279                        if *global == global_id =>
280                    {
281                        *instr = walrus::ir::Instr::Call(walrus::ir::Call {
282                            func: global_set_alt_without_lock,
283                        });
284                    }
285                    walrus::ir::Instr::GlobalGet(walrus::ir::GlobalGet { global })
286                        if *global == global_id =>
287                    {
288                        *instr = walrus::ir::Instr::Call(walrus::ir::Call {
289                            func: global_get_alt_with_lock,
290                        });
291                    }
292                    _ => {}
293                },
294                &[] as &[walrus::FunctionId],
295            )
296            .wrap_err("Failed to rewrite global set/get")?;
297
298        module.globals.delete(global_id);
299
300        module
301            .exports
302            .erase_with(global_set_alt_without_lock, ctx.unstable_print_debug)?;
303        module
304            .exports
305            .erase_with(global_init_alt_without_lock_once, ctx.unstable_print_debug)?;
306        module
307            .exports
308            .erase_with(global_get_alt_with_lock, ctx.unstable_print_debug)?;
309        module
310            .exports
311            .erase_with(global_get_alt_without_lock, ctx.unstable_print_debug)?;
312
313        Ok(())
314    }
315}
316
317impl Generator for SharedGlobal {
318    fn post_lower_memory(
319        &mut self,
320        _module: &mut walrus::Module,
321        ctx: &crate::generator::GeneratorCtx,
322    ) -> eyre::Result<()> {
323        if !matches!(ctx.target_memory_type, TargetMemoryType::Single) {
324            unreachable!();
325        }
326
327        if !ctx.threads {
328            return Ok(());
329        }
330
331        ctx.start_section_builder
332            .as_ref()
333            .unwrap()
334            .add_start_fn(StartFnInfo {
335                priority: StartFnPriority::AfterAll,
336                source: StartSource::Rewrite(Some(Box::new(|module, ctx| {
337                    SharedGlobal::post_lower_memory_inner(module, ctx)
338                }))),
339            });
340
341        Ok(())
342    }
343}
344
345impl SharedGlobal {
346    #[allow(unused_variables)]
347    fn gen_custom_locker(
348        module: &mut walrus::Module,
349        mem_id: walrus::MemoryId,
350        is_debug: bool,
351    ) -> eyre::Result<(walrus::FunctionId, String)> {
352        let alt_id = (
353            "wasip1-vfs_single_memory",
354            &UniqueName::SharedGlobalFns(&SharedGlobalFnsName::MemoryGrowAlt),
355        )
356            .get_fid(&module.imports)?;
357        let base_locker = UniqueName::SharedGlobalFns(&SharedGlobalFnsName::LockerBase)
358            .get_fid(&module.exports)?;
359
360        let locker_id = module.copy_func(base_locker)?;
361
362        let export_name =
363            UniqueName::SharedGlobalFns(&SharedGlobalFnsName::Locker(mem_id.index())).to_string();
364        // todo!(); This is essential for it to function.
365        {
366            module.exports.add(&export_name, locker_id);
367        }
368
369        let locker = module.funcs.get_mut(locker_id);
370
371        use walrus::ir::*;
372
373        locker
374            .kind
375            .unwrap_local_mut()
376            .builder_mut()
377            .func_body()
378            .rewrite(|instr, _| {
379                if let Instr::Call(Call { func }) = instr {
380                    if *func == alt_id {
381                        *instr = Instr::MemoryGrow(MemoryGrow { memory: mem_id });
382                    }
383                }
384            })?;
385
386        Ok((locker_id, export_name))
387    }
388
389    fn remove_gen_custom_locker_base(module: &mut walrus::Module, debug: bool) -> eyre::Result<()> {
390        use walrus::ir::*;
391
392        let alt_id = (
393            "wasip1-vfs_single_memory",
394            &UniqueName::SharedGlobalFns(&SharedGlobalFnsName::MemoryGrowAlt),
395        )
396            .get_fid(&module.imports)?;
397        let base_locker = UniqueName::SharedGlobalFns(&SharedGlobalFnsName::LockerBase)
398            .get_fid(&module.exports)?;
399        if !debug {
400            module.funcs.delete(base_locker);
401            module.funcs.delete(alt_id);
402
403            module.exports.erase_with(base_locker, debug)?;
404        } else {
405            let mem_id = module.memories.iter().next().unwrap().id();
406
407            module
408                .funcs
409                .get_mut(base_locker)
410                .kind
411                .unwrap_local_mut()
412                .builder_mut()
413                .func_body()
414                .rewrite(|instr, _| {
415                    if let Instr::Call(Call { func }) = instr {
416                        if *func == alt_id {
417                            *instr = Instr::MemoryGrow(MemoryGrow { memory: mem_id });
418                        }
419                    }
420                })?;
421        }
422
423        module.imports.erase(alt_id)?;
424
425        Ok(())
426    }
427}