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