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::Generator,
7    instrs::InstrRewrite as _,
8    util::{
9        WalrusFID as _, WalrusUtilExport, WalrusUtilFuncs as _, WalrusUtilImport as _,
10        WalrusUtilModule as _,
11    },
12};
13
14/// https://github.com/WebAssembly/binaryen/issues/7916
15/// 0: Failed to load Wasm file: ./dist\threads_vfs.core.opt.adjusted.wasm
16/// 1: failed to parse global section
17/// 2: malformed mutability -- or shared globals require the shared-everything-threads proposal (at offset 0x49f)
18///
19/// The Globals causing errors during memory expansion are those generated
20/// by wasm-opt --multi-memory-lowering,
21/// so for now we will only address these.
22/// When a newly created thread is executed,
23/// it will use the always-executable VFS code and memory,
24/// which are based on an address that never changes,
25/// and perform operations on them atomically.
26/// Operations on Global variables are replaced,
27/// and before memory unification,
28/// memory.grow is modified to be an atomic operation.
29/// Since this Global variable should only be modified internally,
30/// this approach should be sufficient.
31/// module
32///     .globals
33///     .iter()
34///     .map(|g| g.id())
35///     .collect::<Vec<_>>()
36///     .iter()
37///     .for_each(|g| {
38///         let g = module.globals.get_mut(*g);
39///         if let walrus::GlobalKind::Local(_) = g.kind {
40///             if g.mutable {
41///                 g.shared = true;
42///             }
43///         }
44///     });
45#[derive(Debug, Default)]
46pub struct SharedGlobal;
47
48impl Generator for SharedGlobal {
49    fn post_combine(
50        &mut self,
51        module: &mut walrus::Module,
52        ctx: &crate::generator::GeneratorCtx,
53    ) -> eyre::Result<()> {
54        if !matches!(ctx.target_memory_type, TargetMemoryType::Single) {
55            return Ok(());
56        }
57
58        if !ctx.threads {
59            return Ok(());
60        }
61
62        use std::collections::{HashMap, HashSet};
63        use walrus::ir::*;
64
65        let used_mem_id = module
66            .funcs
67            .all_read(
68                |instr, _| {
69                    if let Instr::MemoryGrow(MemoryGrow { memory, .. }) = instr {
70                        Some(*memory)
71                    } else {
72                        None
73                    }
74                },
75                &[] as &[walrus::FunctionId],
76            )?
77            .into_iter()
78            .filter_map(|v| v)
79            .collect::<HashSet<_>>();
80
81        let lockers = used_mem_id
82            .into_iter()
83            .map(|mem_id| {
84                Self::gen_custom_locker(module, mem_id, ctx.unstable_print_debug)
85                    .wrap_err("Failed to generate custom locker function")
86                    .map(|locker_id| (mem_id, locker_id))
87            })
88            .collect::<eyre::Result<HashMap<_, _>>>()?;
89
90        Self::remove_gen_custom_locker_base(module, ctx.unstable_print_debug)
91            .wrap_err("Failed to remove base locker function")?;
92
93        module.funcs.all_rewrite(
94            |instr, _| {
95                if let Instr::MemoryGrow(MemoryGrow { memory, .. }) = instr {
96                    *instr = Instr::Call(Call {
97                        func: lockers.get(memory).unwrap().to_owned(),
98                    });
99                }
100            },
101            &lockers.values().cloned().collect::<Vec<_>>(),
102        )?;
103
104        Ok(())
105    }
106
107    fn post_lower_memory(
108        &mut self,
109        module: &mut walrus::Module,
110        ctx: &crate::generator::GeneratorCtx,
111    ) -> eyre::Result<()> {
112        if !matches!(ctx.target_memory_type, TargetMemoryType::Single) {
113            return Ok(());
114        }
115
116        if !ctx.threads {
117            return Ok(());
118        }
119
120        let global_set_alt_without_lock =
121            "__wasip1_vfs_memory_grow_global_alt_set".get_fid(&module.exports)?;
122        let global_init_alt_without_lock_once =
123            "__wasip1_vfs_memory_grow_global_alt_init_once".get_fid(&module.exports)?;
124        let global_get_alt_with_lock =
125            "__wasip1_vfs_memory_grow_global_alt_get".get_fid(&module.exports)?;
126        let global_get_alt_without_lock =
127            "__wasip1_vfs_memory_grow_global_alt_get_no_wait".get_fid(&module.exports)?;
128
129        let global = module
130            .globals
131            .iter()
132            .last()
133            .map(|g| g)
134            .wrap_err_with(|| eyre::eyre!("Failed to get global ID"))?;
135
136        let init = match global.kind {
137            walrus::GlobalKind::Local(walrus::ConstExpr::Value(walrus::ir::Value::I32(value))) => {
138                value
139            }
140            _ => unreachable!(),
141        };
142
143        let global_id = global.id();
144
145        // Obtain the location within memory.
146        let global_alt_pos = "__wasip1_vfs_memory_grow_global_alt_pos".get_fid(&module.exports)?;
147        // let global_alt_pos = module.funcs.get(global_alt_pos).kind.unwrap_local();
148        // let global_alt_pos = if let walrus::ir::Instr::Const(walrus::ir::Const {
149        //     value: walrus::ir::Value::I32(value),
150        // }) = global_alt_pos
151        //     .block(global_alt_pos.entry_block())
152        //     .instrs
153        //     .first()
154        //     .unwrap()
155        //     .0
156        // {
157        //     value
158        // } else {
159        //     unreachable!()
160        // };
161        module
162            .exports
163            .erase_with(global_alt_pos, ctx.unstable_print_debug)?;
164
165        // check global set in start section function
166        let start_id = if let Some(id) = module.start {
167            module
168                .nested_copy_func(id, &[id], false, false)
169                .wrap_err("Failed to create start function copy")?
170        } else {
171            // create a new start function
172            module.add_func(&[], &[], |_, _| Ok(()))?
173        };
174        module.start = Some(start_id);
175
176        if 0usize
177            < module
178                .funcs
179                .flat_rewrite(
180                    |instr, _| match instr {
181                        walrus::ir::Instr::GlobalSet(walrus::ir::GlobalSet { global })
182                            if *global == global_id =>
183                        {
184                            1usize
185                        }
186                        walrus::ir::Instr::GlobalGet(walrus::ir::GlobalGet { global })
187                            if *global == global_id =>
188                        {
189                            *instr = walrus::ir::Instr::Const(walrus::ir::Const {
190                                value: walrus::ir::Value::I32(init),
191                            });
192                            // println!("Rewrote global get to const i32 {init}");
193                            0usize
194                        }
195                        _ => 0usize,
196                    },
197                    start_id,
198                    false,
199                )?
200                .into_iter()
201                .sum()
202        {
203            eyre::bail!(
204                "The start section already contains a global set instruction. \
205                Please remove it manually and try again."
206            );
207        }
208
209        let start_local = module.funcs.get_mut(start_id).kind.unwrap_local_mut();
210        start_local
211            .builder_mut()
212            .func_body()
213            .i32_const(init)
214            .call(global_init_alt_without_lock_once);
215
216        let lockers = module
217            .exports
218            .iter()
219            .filter_map(|e| {
220                if e.name.starts_with("__wasip1_vfs_memory_grow_locker_") {
221                    if let walrus::ExportItem::Function(fid) = e.item {
222                        Some(fid)
223                    } else {
224                        None
225                    }
226                } else {
227                    None
228                }
229            })
230            .collect::<Vec<_>>();
231
232        // The locker is locked at the point it is called. So we can replace
233        for locker_id in lockers {
234            // println!("Rewriting locker: {:?}", locker_id);
235            use walrus::ir::*;
236            let new_locker =
237                // module.nested_copy_func(locker_id, &[] as &[FunctionId], false, false)?;
238                module.nested_copy_func(locker_id, &[] as &[FunctionId], true, true)?;
239
240            module.funcs.flat_rewrite(
241                |instr, _| match instr {
242                    Instr::GlobalGet(GlobalGet { global }) if *global == global_id => {
243                        *instr = Instr::Call(Call {
244                            func: global_get_alt_without_lock,
245                        });
246                    }
247                    _ => {}
248                },
249                new_locker,
250                true,
251            )?;
252
253            module.renew_call_fn(locker_id, new_locker)?;
254        }
255
256        module
257            .funcs
258            .all_rewrite(
259                |instr, _| match instr {
260                    walrus::ir::Instr::GlobalSet(walrus::ir::GlobalSet { global })
261                        if *global == global_id =>
262                    {
263                        *instr = walrus::ir::Instr::Call(walrus::ir::Call {
264                            func: global_set_alt_without_lock,
265                        });
266                    }
267                    walrus::ir::Instr::GlobalGet(walrus::ir::GlobalGet { global })
268                        if *global == global_id =>
269                    {
270                        *instr = walrus::ir::Instr::Call(walrus::ir::Call {
271                            func: global_get_alt_with_lock,
272                        });
273                    }
274                    _ => {}
275                },
276                &[] as &[walrus::FunctionId],
277            )
278            .wrap_err("Failed to rewrite global set/get")?;
279
280        module.globals.delete(global_id);
281
282        module
283            .exports
284            .erase_with(global_set_alt_without_lock, ctx.unstable_print_debug)?;
285        module
286            .exports
287            .erase_with(global_init_alt_without_lock_once, ctx.unstable_print_debug)?;
288        module
289            .exports
290            .erase_with(global_get_alt_with_lock, ctx.unstable_print_debug)?;
291        module
292            .exports
293            .erase_with(global_get_alt_without_lock, ctx.unstable_print_debug)?;
294
295        Ok(())
296    }
297}
298
299impl SharedGlobal {
300    fn gen_custom_locker(
301        module: &mut walrus::Module,
302        mem_id: walrus::MemoryId,
303        is_debug: bool,
304    ) -> eyre::Result<walrus::FunctionId> {
305        let alt_id = ("wasip1-vfs_single_memory", "__wasip1_vfs_memory_grow_alt")
306            .get_fid(&module.imports)?;
307        let base_locker = "__wasip1_vfs_memory_grow_locker".get_fid(&module.exports)?;
308
309        let locker_id = module.copy_func(base_locker)?;
310        if is_debug {
311            module.exports.add(
312                &format!("__wasip1_vfs_memory_grow_locker_{}", mem_id.index()),
313                locker_id,
314            );
315        }
316
317        let locker = module.funcs.get_mut(locker_id);
318
319        use walrus::ir::*;
320
321        locker
322            .kind
323            .unwrap_local_mut()
324            .builder_mut()
325            .func_body()
326            .rewrite(|instr, _| {
327                if let Instr::Call(Call { func }) = instr {
328                    if *func == alt_id {
329                        *instr = Instr::MemoryGrow(MemoryGrow { memory: mem_id });
330                    }
331                }
332            })?;
333
334        Ok(locker_id)
335    }
336
337    fn remove_gen_custom_locker_base(module: &mut walrus::Module, debug: bool) -> eyre::Result<()> {
338        use walrus::ir::*;
339
340        let alt_id = ("wasip1-vfs_single_memory", "__wasip1_vfs_memory_grow_alt")
341            .get_fid(&module.imports)?;
342        let base_locker = "__wasip1_vfs_memory_grow_locker".get_fid(&module.exports)?;
343        if !debug {
344            module.funcs.delete(base_locker);
345            module.funcs.delete(alt_id);
346
347            module.exports.erase_with(base_locker, debug)?;
348        } else {
349            let mem_id = module.memories.iter().next().unwrap().id();
350
351            module
352                .funcs
353                .get_mut(base_locker)
354                .kind
355                .unwrap_local_mut()
356                .builder_mut()
357                .func_body()
358                .rewrite(|instr, _| {
359                    if let Instr::Call(Call { func }) = instr {
360                        if *func == alt_id {
361                            *instr = Instr::MemoryGrow(MemoryGrow { memory: mem_id });
362                        }
363                    }
364                })?;
365        }
366
367        module.imports.erase(alt_id)?;
368
369        Ok(())
370    }
371}