wasi_virt_layer-cli 0.2.2

CLI for the wasi_virt_layer crate
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
use eyre::{Context as _, ContextCompat as _};
use walrus::FunctionId;

use crate::{
    args::TargetMemoryType,
    generator::{
        Generator,
        start_section::{StartFnInfo, StartFnPriority, StartSource},
    },
    instrs::InstrRewrite as _,
    unique_name::UniqueName,
    util::{
        WalrusFID as _, WalrusUtilExport, WalrusUtilFuncs as _, WalrusUtilImport as _,
        WalrusUtilModule as _,
    },
};

/// https://github.com/WebAssembly/binaryen/issues/7916
/// 0: Failed to load Wasm file: ./dist\threads_vfs.core.opt.adjusted.wasm
/// 1: failed to parse global section
/// 2: malformed mutability -- or shared globals require the shared-everything-threads proposal (at offset 0x49f)
///
/// The Globals causing errors during memory expansion are those generated
/// by wasm-opt --multi-memory-lowering,
/// so for now we will only address these.
/// When a newly created thread is executed,
/// it will use the always-executable VFS code and memory,
/// which are based on an address that never changes,
/// and perform operations on them atomically.
/// Operations on Global variables are replaced,
/// and before memory unification,
/// memory.grow is modified to be an atomic operation.
/// Since this Global variable should only be modified internally,
/// this approach should be sufficient.
/// module
///     .globals
///     .iter()
///     .map(|g| g.id())
///     .collect::<Vec<_>>()
///     .iter()
///     .for_each(|g| {
///         let g = module.globals.get_mut(*g);
///         if let walrus::GlobalKind::Local(_) = g.kind {
///             if g.mutable {
///                 g.shared = true;
///             }
///         }
///     });
/// Generator responsible for managing globally shared variables to enable multi-threading atomic modifications.
#[derive(Debug, Default)]
pub struct SharedGlobal;

/// Enum containing identifiers for alternative shared global function replacements and locker usages.
#[derive(Debug, strum::AsRefStr, strum::EnumCount, PartialEq, Eq, Hash)]
#[strum(serialize_all = "snake_case")]
pub enum SharedGlobalFnsName {
    /// Wrapper replacing a global variable assignment internally without locking overhead.
    GlobalAltSet,
    /// Thread-safe wrapper evaluating and retrieving the global value.
    GlobalAltGet,
    /// Fast wrapper evaluating the global value bypassing thread synchronization lock operations.
    GlobalAltGetNoWait,
    /// Singleton wrapper assigning an initializing value solely on a one-time startup sequence.
    GlobalAltInitOnce,
    /// Utility function yielding the exact offset index memory location storing the global proxy.
    GlobalAltPos,
    /// Locking function instance controlling concurrent memory accesses for a specific table identified by index.
    Locker(usize),
    #[strum(serialize = "locker")]
    /// Uniquely identified primary initial lock mechanism controlling baseline single-memory environments.
    LockerBase,
    #[strum(serialize = "alt")]
    /// Replaced function logic hooking WebAssembly natively executed `memory.grow` allocation algorithms.
    MemoryGrowAlt,
}

impl SharedGlobalFnsName {
    /// Checks whether the provided string identifier maps to a locker operation, extracting its index.
    pub fn check_locker(str: impl AsRef<str>) -> Option<SharedGlobalFnsName> {
        let s = str.as_ref();
        let prefix = crate::unique_name::fmt!(SharedGlobalFns; "{}", SharedGlobalFnsName::Locker(0).as_ref());
        if s.starts_with(&prefix) && s.len() > prefix.len() {
            let index_str = &s[prefix.len() + 1..];
            if let Ok(index) = index_str.parse::<usize>() {
                return Some(SharedGlobalFnsName::Locker(index));
            }
        }
        None
    }
}

impl SharedGlobal {
    fn post_lower_memory_inner(
        module: &mut walrus::Module,
        ctx: &crate::generator::GeneratorCtx,
    ) -> eyre::Result<()> {
        use std::collections::{HashMap, HashSet};
        use walrus::ir::*;

        if !matches!(ctx.target_memory_type, TargetMemoryType::Single) {
            unreachable!();
        }

        if !ctx.threads {
            return Ok(());
        }

        let used_mem_id = module
            .funcs
            .all_read(
                |instr, _| {
                    if let Instr::MemoryGrow(MemoryGrow { memory, .. }) = instr {
                        Some(*memory)
                    } else {
                        None
                    }
                },
                &[] as &[walrus::FunctionId],
            )?
            .into_iter()
            .filter_map(|v| v)
            .collect::<HashSet<_>>();

        let lockers = used_mem_id
            .into_iter()
            .map(|mem_id| {
                Self::gen_custom_locker(module, mem_id, ctx.unstable_print_debug)
                    .wrap_err("Failed to generate custom locker function")
                    .map(|(locker_id, export_name)| (mem_id, (locker_id, export_name)))
            })
            .collect::<eyre::Result<HashMap<_, _>>>()?;

        Self::remove_gen_custom_locker_base(module, ctx.unstable_print_debug)
            .wrap_err("Failed to remove base locker function")?;

        module.funcs.all_rewrite(
            |instr, _| {
                if let Instr::MemoryGrow(MemoryGrow { memory, .. }) = instr {
                    *instr = Instr::Call(Call {
                        func: lockers.get(memory).unwrap().to_owned().0,
                    });
                }
            },
            &lockers.values().map(|(v, _)| *v).collect::<Vec<_>>(),
        )?;

        let global_set_alt_without_lock =
            UniqueName::SharedGlobalFns(&SharedGlobalFnsName::GlobalAltSet)
                .get_fid(&module.exports)?;
        let global_init_alt_without_lock_once =
            UniqueName::SharedGlobalFns(&SharedGlobalFnsName::GlobalAltInitOnce)
                .get_fid(&module.exports)?;
        let global_get_alt_with_lock =
            UniqueName::SharedGlobalFns(&SharedGlobalFnsName::GlobalAltGet)
                .get_fid(&module.exports)?;
        let global_get_alt_without_lock =
            UniqueName::SharedGlobalFns(&SharedGlobalFnsName::GlobalAltGetNoWait)
                .get_fid(&module.exports)?;

        let global = module
            .globals
            .iter()
            .last()
            .map(|g| g)
            .wrap_err_with(|| eyre::eyre!("Failed to get global ID"))?;

        let init = match global.kind {
            walrus::GlobalKind::Local(walrus::ConstExpr::Value(walrus::ir::Value::I32(value))) => {
                value
            }
            _ => unreachable!(),
        };

        let global_id = global.id();

        // Obtain the location within memory.
        let global_alt_pos = UniqueName::SharedGlobalFns(&SharedGlobalFnsName::GlobalAltPos)
            .get_fid(&module.exports)?;
        // let global_alt_pos = module.funcs.get(global_alt_pos).kind.unwrap_local();
        // let global_alt_pos = if let walrus::ir::Instr::Const(walrus::ir::Const {
        //     value: walrus::ir::Value::I32(value),
        // }) = global_alt_pos
        //     .block(global_alt_pos.entry_block())
        //     .instrs
        //     .first()
        //     .unwrap()
        //     .0
        // {
        //     value
        // } else {
        //     unreachable!()
        // };
        module
            .exports
            .erase_with(global_alt_pos, ctx.unstable_print_debug)?;

        // check global set in start section function
        let start_id = if let Some(id) = module.start {
            module
                .nested_copy_func(id, &[id], false, false)
                .wrap_err("Failed to create start function copy")?
        } else {
            // create a new start function
            module.add_func(&[], &[], |_, _| Ok(()))?
        };
        module.start = Some(start_id);

        if 0usize
            < module
                .funcs
                .flat_rewrite(
                    |instr, _| match instr {
                        walrus::ir::Instr::GlobalSet(walrus::ir::GlobalSet { global })
                            if *global == global_id =>
                        {
                            1usize
                        }
                        walrus::ir::Instr::GlobalGet(walrus::ir::GlobalGet { global })
                            if *global == global_id =>
                        {
                            *instr = walrus::ir::Instr::Const(walrus::ir::Const {
                                value: walrus::ir::Value::I32(init),
                            });
                            // println!("Rewrote global get to const i32 {init}");
                            0usize
                        }
                        _ => 0usize,
                    },
                    start_id,
                    false,
                )?
                .into_iter()
                .sum()
        {
            eyre::bail!(
                "The start section already contains a global set instruction. \
                Please remove it manually and try again."
            );
        }

        let start_local = module.funcs.get_mut(start_id).kind.unwrap_local_mut();
        start_local
            .builder_mut()
            .func_body()
            .i32_const(init)
            .call(global_init_alt_without_lock_once);

        // The locker is locked at the point it is called. So we can replace
        for (_, (locker_id, name)) in lockers {
            // println!("Rewriting locker: {:?}", locker_id);
            use walrus::ir::*;
            let new_locker =
                // module.nested_copy_func(locker_id, &[] as &[FunctionId], false, false)?;
                module.nested_copy_func(locker_id, &[] as &[FunctionId], true, true)?;

            module.funcs.flat_rewrite(
                |instr, _| match instr {
                    Instr::GlobalGet(GlobalGet { global }) if *global == global_id => {
                        *instr = Instr::Call(Call {
                            func: global_get_alt_without_lock,
                        });
                    }
                    _ => {}
                },
                new_locker,
                true,
            )?;

            module.renew_call_fn(locker_id, new_locker)?;

            module.exports.erase_with(&name, ctx.unstable_print_debug)?;
        }

        module
            .funcs
            .all_rewrite(
                |instr, _| match instr {
                    walrus::ir::Instr::GlobalSet(walrus::ir::GlobalSet { global })
                        if *global == global_id =>
                    {
                        *instr = walrus::ir::Instr::Call(walrus::ir::Call {
                            func: global_set_alt_without_lock,
                        });
                    }
                    walrus::ir::Instr::GlobalGet(walrus::ir::GlobalGet { global })
                        if *global == global_id =>
                    {
                        *instr = walrus::ir::Instr::Call(walrus::ir::Call {
                            func: global_get_alt_with_lock,
                        });
                    }
                    _ => {}
                },
                &[] as &[walrus::FunctionId],
            )
            .wrap_err("Failed to rewrite global set/get")?;

        module.globals.delete(global_id);

        module
            .exports
            .erase_with(global_set_alt_without_lock, ctx.unstable_print_debug)?;
        module
            .exports
            .erase_with(global_init_alt_without_lock_once, ctx.unstable_print_debug)?;
        module
            .exports
            .erase_with(global_get_alt_with_lock, ctx.unstable_print_debug)?;
        module
            .exports
            .erase_with(global_get_alt_without_lock, ctx.unstable_print_debug)?;

        Ok(())
    }
}

impl Generator for SharedGlobal {
    fn post_lower_memory(
        &mut self,
        _module: &mut walrus::Module,
        ctx: &crate::generator::GeneratorCtx,
    ) -> eyre::Result<()> {
        if !matches!(ctx.target_memory_type, TargetMemoryType::Single) {
            unreachable!();
        }

        if !ctx.threads {
            return Ok(());
        }

        ctx.start_section_builder
            .as_ref()
            .unwrap()
            .add_start_fn(StartFnInfo {
                priority: StartFnPriority::AfterAll,
                source: StartSource::Rewrite(Some(Box::new(|module, ctx| {
                    SharedGlobal::post_lower_memory_inner(module, ctx)
                }))),
            });

        Ok(())
    }
}

impl SharedGlobal {
    #[allow(unused_variables)]
    fn gen_custom_locker(
        module: &mut walrus::Module,
        mem_id: walrus::MemoryId,
        is_debug: bool,
    ) -> eyre::Result<(walrus::FunctionId, String)> {
        let alt_id = (
            "wasip1-vfs_single_memory",
            &UniqueName::SharedGlobalFns(&SharedGlobalFnsName::MemoryGrowAlt),
        )
            .get_fid(&module.imports)?;
        let base_locker = UniqueName::SharedGlobalFns(&SharedGlobalFnsName::LockerBase)
            .get_fid(&module.exports)?;

        let locker_id = module.copy_func(base_locker)?;

        let export_name =
            UniqueName::SharedGlobalFns(&SharedGlobalFnsName::Locker(mem_id.index())).to_string();
        // todo!(); This is essential for it to function.
        {
            module.exports.add(&export_name, locker_id);
        }

        let locker = module.funcs.get_mut(locker_id);

        use walrus::ir::*;

        locker
            .kind
            .unwrap_local_mut()
            .builder_mut()
            .func_body()
            .rewrite(|instr, _| {
                if let Instr::Call(Call { func }) = instr {
                    if *func == alt_id {
                        *instr = Instr::MemoryGrow(MemoryGrow { memory: mem_id });
                    }
                }
            })?;

        Ok((locker_id, export_name))
    }

    fn remove_gen_custom_locker_base(module: &mut walrus::Module, debug: bool) -> eyre::Result<()> {
        use walrus::ir::*;

        let alt_id = (
            "wasip1-vfs_single_memory",
            &UniqueName::SharedGlobalFns(&SharedGlobalFnsName::MemoryGrowAlt),
        )
            .get_fid(&module.imports)?;
        let base_locker = UniqueName::SharedGlobalFns(&SharedGlobalFnsName::LockerBase)
            .get_fid(&module.exports)?;
        if !debug {
            module.funcs.delete(base_locker);
            module.funcs.delete(alt_id);

            module.exports.erase_with(base_locker, debug)?;
        } else {
            let mem_id = module.memories.iter().next().unwrap().id();

            module
                .funcs
                .get_mut(base_locker)
                .kind
                .unwrap_local_mut()
                .builder_mut()
                .func_body()
                .rewrite(|instr, _| {
                    if let Instr::Call(Call { func }) = instr {
                        if *func == alt_id {
                            *instr = Instr::MemoryGrow(MemoryGrow { memory: mem_id });
                        }
                    }
                })?;
        }

        module.imports.erase(alt_id)?;

        Ok(())
    }
}