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
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
use std::{collections::HashMap, str::FromStr};

use eyre::{Context as _, ContextCompat as _};
use walrus::ir;

use crate::{
    args::TargetMemoryType,
    generator::{ComponentCtx, Generator, GeneratorCtx},
    unique_name::UniqueName,
    util::{ResultUtil as _, WalrusFID, WalrusUtilExport, WalrusUtilModule, WasmName},
};

/// Encapsulates naming variants reserved for VFS memory interactions.
#[derive(Debug, strum::AsRefStr, strum::EnumCount, Hash, PartialEq, Eq, strum::VariantNames)]
#[strum(serialize_all = "snake_case")]
pub enum MemoryUniqueName<'a> {
    /// Copies contents from Target Memory to VFS Memory.
    MemoryCopyFrom(&'a WasmName),
    /// Copies contents from VFS Memory to Target Memory.
    MemoryCopyTo(&'a WasmName),
    /// Emplaces a runtime trap to deduce pointer arithmetic limits.
    MemoryTrap(&'a WasmName),
    /// Serves as a linked anchor ensuring `MemoryTrap` preserves its compiled identity.
    MemoryTrapAnchor(&'a WasmName),
    /// Wraps dynamic function dispatch controlling pointers to merged targets.
    MemoryDirector(&'a WasmName),
    /// Serves as a linked anchor preserving the compiled `MemoryDirector` identity.
    MemoryDirectorAnchor(&'a WasmName),
    /// The fundamental reference identifying the exported memory location of the underlying module.
    Memory(&'a WasmName),
}

/// ABI Generator: Manages memory configurations temporarily during transpilation.
///
/// **Why this is needed:**
/// Certain WebAssembly translating/optimizing tools cannot handle shared memory or multiple memories
/// if threading features are disabled or unavailable in the environment. This generator temporarily
/// unshares imported memory, performs the component transformations, and then properly re-links
/// or re-shares the memory so the VFS has correct access to the target modules' structures.
#[derive(Debug, Default)]
pub struct TemporaryRefugeMemory {
    /// Indicates the overall tracked quantity of memory blocks actively transpiled.
    pub memory_count: usize,
}

impl TemporaryRefugeMemory {
    /// Standardizes the component structure and ensures temporary threading parameters accommodate memory translations.
    pub fn ready_component_and_transpile(
        &mut self,
        module: &mut walrus::Module,
        _ctx: &GeneratorCtx,
    ) -> eyre::Result<()> {
        let mut is_first = false;

        let mut imported_memories = Vec::new();
        let mut shared_memories = Vec::new();

        let mut mem_names = HashMap::new();

        module
            .memories
            .iter_mut()
            .map(|mem| {
                let id = mem.id();

                if let Some(mem_id) = mem.import {
                    imported_memories.push(id);
                    let import = module.imports.get(mem_id);
                    let name = import.name.clone();
                    module.imports.delete(mem_id);
                    mem.import = None;
                    if mem_names.values().any(|s| *s == name) {
                        let n = (1..)
                            .find(|n| !mem_names.values().any(|s| *s == format!("{name}_{n}")))
                            .unwrap();
                        mem_names.insert(id, format!("{name}_{n}"));
                    } else {
                        mem_names.insert(id, name);
                    }
                }

                // Translating component requires WasmFeatures::Threads
                // but we cannot enable it because it in other crates.
                // So, we set shared to false here temporarily.
                if mem.shared {
                    if !is_first {
                        is_first = true;
                        log::warn!(
                            r"Transpiling with threads is not supported yet. so this wasm off memory shared flag and can't be used as it is. {mem:?}"
                        );
                    }

                    shared_memories.push(id);
                    mem.shared = false;
                }

                Ok(())
            })
            .collect::<eyre::Result<Vec<_>>>()?;

        for (n, mem_id) in module
            .memories
            .iter()
            .map(|mem| mem.id())
            .enumerate()
            .collect::<Box<_>>()
        {
            module.create_memory_anchor_with_info(
                format!("__wasip1_vfs_memory_anchor_{n}"),
                mem_id,
                Some(HadSharedAndImported {
                    had_shared: shared_memories.contains(&mem_id),
                    had_imported: imported_memories.contains(&mem_id),
                    name: mem_names.get(&mem_id).cloned(),
                }),
            )?;
        }

        self.memory_count = module.memories.iter().count();

        module
            .save_info("memory_count", self.memory_count)
            .wrap_err("Failed to save memory_count")?;

        Ok(())
    }
}

#[derive(Debug, Clone)]
struct HadSharedAndImported {
    pub had_shared: bool,
    pub had_imported: bool,
    pub name: Option<String>,
}

impl ToString for HadSharedAndImported {
    fn to_string(&self) -> String {
        let n = self.had_shared as u8
            | (self.had_imported as u8) << 1
            | (self.name.is_some() as u8) << 2;
        format!("{n}{}", self.name.as_ref().unwrap_or(&"".into()))
    }
}

impl FromStr for HadSharedAndImported {
    type Err = eyre::Report;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let n = s[0..1]
            .parse::<u8>()
            .wrap_err_with(|| eyre::eyre!("Failed to parse HadSharedAndImported from {s}"))?;
        let name = if n & 4 != 0 {
            Some(s[1..].to_string())
        } else {
            None
        };
        Ok(Self {
            had_shared: (n & 1) != 0,
            had_imported: (n & 2) != 0,
            name,
        })
    }
}

impl Generator for TemporaryRefugeMemory {
    fn pre_target(
        &mut self,
        module: &mut walrus::Module,
        _: &GeneratorCtx,
        external: &crate::generator::ModuleExternal,
    ) -> eyre::Result<()> {
        module
            .exports
            .iter_mut()
            .find(|export| export.name == "memory")
            .unwrap()
            .name = UniqueName::Memory(&MemoryUniqueName::Memory(&external.name)).to_string();

        Ok(())
    }

    fn post_combine(
        &mut self,
        module: &mut walrus::Module,
        ctx: &GeneratorCtx,
    ) -> eyre::Result<()> {
        // Remove memory exports outside of VFS.
        // Connect all non-VFS ABIs to VFS and hide them.
        let mem_export_id = module
            .exports
            .iter()
            .filter(|export|
                matches!(export.item, walrus::ExportItem::Memory(mem) if ctx.vfs_used_memory_id.as_ref().unwrap() != &mem)
            )
            .map(|export| export.id())
            .collect::<Vec<_>>();

        for id in mem_export_id {
            module.exports.delete(id);
        }

        // rename vfs memory export to memory
        module
            .memories
            .get_mut(ctx.vfs_used_memory_id.unwrap())
            .name = Some("memory".to_string());
        module
            .exports
            .get_mut(
                module
                    .exports
                    .get_exported_memory(ctx.vfs_used_memory_id.unwrap())
                    .unwrap()
                    .id(),
            )
            .name = "memory".to_string();

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

        if ctx.target_memory_type == TargetMemoryType::Multi {
            self.ready_component_and_transpile(module, ctx)?;
        } else {
            module
                .memories
                .iter_mut()
                .filter(|mem| mem.id() != *ctx.vfs_used_memory_id.as_ref().unwrap())
                .map(|mem| {
                    let id = mem.id();
                    let mem_id = module.imports.iter().find_map(|import| match import.kind {
                        walrus::ImportKind::Memory(mid) if mid == id => Some(import.id()),
                        _ => None,
                    });

                    if let Some(mem_id) = mem_id {
                        module.imports.delete(mem_id);
                        mem.import = None;
                    }

                    Ok(())
                })
                .collect::<eyre::Result<Vec<_>>>()?;
        }

        Ok(())
    }

    fn post_lower_memory(
        &mut self,
        module: &mut walrus::Module,
        ctx: &GeneratorCtx,
    ) -> eyre::Result<()> {
        if !ctx.threads {
            return Ok(());
        }

        self.ready_component_and_transpile(module, ctx)?;

        Ok(())
    }

    fn post_components(
        &mut self,
        module: &mut walrus::Module,
        ctx: &ComponentCtx,
    ) -> eyre::Result<()> {
        if !ctx.threads() {
            return Ok(());
        }

        self.memory_count = module
            .load_info::<usize>("memory_count")
            .wrap_err("Failed to load memory_count")?;

        for count in 0..self.memory_count {
            let (id, info) = module
                .get_memory_anchor_with_info::<HadSharedAndImported>(
                    &format!("__wasip1_vfs_memory_anchor_{count}"),
                    true,
                )
                .wrap_err("cannot find info, you may change anchor name")?;
            let info = info.unwrap();
            let mem = module.memories.get_mut(id);

            mem.name = info.name.clone();

            if info.had_imported {
                let import_id = module.imports.add(
                    "env",
                    &info.name.unwrap(),
                    walrus::ImportKind::Memory(mem.id()),
                );

                mem.import = Some(import_id);
            }
            if info.had_shared {
                mem.shared = true;
            }
        }

        Ok(())
    }
}

/// When exchanging data via Wasip1ABI,
/// there are operations involving writing to
/// and reading from memory.
/// However, as these cannot be accessed during compilation,
/// alternative functions are employed. These shall be replaced.
///
/// **Why this is needed:**
/// Since the VFS layer needs to transfer data between its own memory and the guest's memory
/// when processing ABI calls, it defines `memory_copy_from` and `memory_copy_to` as external imports.
/// Since `walrus` does not allow generating components with unknown raw imports, this generator
/// patches those structural import declarations with native `memory.copy` WebAssembly instructions
/// executing over the correct `multi-memory` tables.
#[derive(Debug, Default)]
pub struct MemoryBridge;

macro_rules! assert_ptr {
    ($ptr:expr) => {
        if { $ptr } != walrus::ValType::I32 {
            let ptr = $ptr;
            eyre::bail!("Invalid pointer type, expected i32. Got {ptr}");
        }
    };
}

macro_rules! assert_len {
    ($len:expr) => {
        if { $len } != walrus::ValType::I32 {
            let len = $len;
            eyre::bail!("Invalid length type, expected i32. Got {len}");
        }
    };
}

macro_rules! check_len {
    ($params:expr, $len:expr) => {
        if { $params.len() } != { $len } {
            let len = $len;
            eyre::bail!(
                "Invalid params length, expected {len}. Got {}",
                { $params }.len()
            );
        }
    };
}

impl Generator for MemoryBridge {
    fn post_combine(
        &mut self,
        module: &mut walrus::Module,
        ctx: &GeneratorCtx,
    ) -> eyre::Result<()> {
        for wasm in &ctx.target_names {
            let wasm_mem = ctx.target_used_memory_id.as_ref().unwrap()[wasm];
            let vfs_mem = ctx.vfs_used_memory_id.unwrap();

            if let Some(id) = (
                UniqueName::NAMESPACE,
                &UniqueName::Memory(&MemoryUniqueName::MemoryCopyFrom(wasm)),
            )
                .get_fid(&module.imports)
                .ok()
            {
                let func = module.funcs.get(id);
                let ty = module.types.get(func.ty());
                let params = ty.params();

                check_len!(params, 3);
                assert_ptr!(params[0]); // offset
                assert_ptr!(params[1]); // src
                assert_len!(params[2]); // len
                check_len!(ty.results(), 0);

                module
                    .replace_imported_func(id, |(body, args)| {
                        body.local_get(args[0])
                            .local_get(args[1])
                            .local_get(args[2])
                            .memory_copy(vfs_mem, wasm_mem);
                    })
                    .to_eyre()
                    .wrap_err_with(|| eyre::eyre!("Failed to replace memory_copy_from"))?;
            }

            if let Some(id) = (
                UniqueName::NAMESPACE,
                &UniqueName::Memory(&MemoryUniqueName::MemoryCopyTo(wasm)),
            )
                .get_fid(&module.imports)
                .ok()
            {
                let func = module.funcs.get(id);
                let ty = module.types.get(func.ty());
                let params = ty.params();

                check_len!(params, 3);
                assert_ptr!(params[0]); // offset
                assert_ptr!(params[1]); // src
                assert_len!(params[2]); // len
                check_len!(ty.results(), 0);

                module
                    .replace_imported_func(id, |(body, args)| {
                        body.local_get(args[0])
                            .local_get(args[1])
                            .local_get(args[2])
                            .memory_copy(wasm_mem, vfs_mem);
                    })
                    .to_eyre()
                    .wrap_err_with(|| eyre::eyre!("Failed to replace memory_copy_to"))?;
            }
        }

        Ok(())
    }
}

/// The final wasm, due to ABI constraints,
/// only exposes vfs memory.
/// Therefore, when calling the ABI from non-vfs memory,
/// data must be copied. However,
/// when ultimately consolidating memory into a single pool,
/// data can be passed externally by directly passing pointers.
/// To implement this optimization,
/// a function is provided to determine the pointer bias
/// before memory consolidation.
///
/// **Why this is needed:**
/// If running in `single_memory` mode (without the `multi_memory` WASM feature), all modules'
/// memories are merged into one large address space. The VFS needs to know where the guest
/// module's memory segment actually resides within this merged pool. This generator uses a trap
/// mechanism to securely determine the actual pointer bias at runtime so external callers and
/// the VFS can translate addresses correctly.
#[derive(Debug, Default)]
pub struct MemoryTrap;

impl Generator for MemoryTrap {
    fn post_combine(
        &mut self,
        module: &mut walrus::Module,
        ctx: &GeneratorCtx,
    ) -> eyre::Result<()> {
        if matches!(ctx.target_memory_type, TargetMemoryType::Multi) {
            return Ok(());
        }

        for wasm in &ctx.target_names {
            if let Some(id) = (
                UniqueName::NAMESPACE,
                &UniqueName::Memory(&MemoryUniqueName::MemoryTrap(wasm)),
            )
                .get_fid(&module.imports)
                .ok()
            {
                let func = module.funcs.get(id);
                let ty = module.types.get(func.ty());
                let params = ty.params();

                check_len!(params, 1);
                assert_ptr!(params[0]); // offset
                check_len!(ty.results(), 1);
                assert_ptr!(ty.results()[0]); // result

                let wasm_mem = ctx.target_used_memory_id.as_ref().unwrap()[wasm];

                module
                    .replace_imported_func(id, |(body, args)| {
                        body.local_get(args[0])
                            .i32_const(0)
                            .store(
                                wasm_mem,
                                ir::StoreKind::I32_8 { atomic: false },
                                ir::MemArg {
                                    align: 0,
                                    offset: 0,
                                },
                            )
                            .i32_const(0);
                    })
                    .to_eyre()
                    .wrap_err_with(|| eyre::eyre!("Failed to replace memory_trap"))?;
            }
        }

        Ok(())
    }

    fn post_lower_memory(
        &mut self,
        module: &mut walrus::Module,
        ctx: &GeneratorCtx,
    ) -> eyre::Result<()> {
        if matches!(ctx.target_memory_type, TargetMemoryType::Multi) {
            return Ok(());
        }

        for wasm in &ctx.target_names {
            let trap_export_name =
                UniqueName::Memory(&MemoryUniqueName::MemoryTrapAnchor(wasm)).to_string();
            let trap_id = trap_export_name
                .get_fid(&module.exports)
                .wrap_err_with(|| {
                    eyre::eyre!("Failed to get {trap_export_name} export on {wasm}.")
                })?;

            module
                .exports
                .erase_with(trap_id, ctx.unstable_print_debug)?;

            let trap_body = module.funcs.get_mut(trap_id).kind.unwrap_local_mut();
            let trap_body = trap_body.block_mut(trap_body.entry_block());

            // Remove the fake value instruction
            // Optimization may have significantly altered the content,
            // but I'll put it off for now.
            let (store_index, store_info) = trap_body
                .iter()
                .enumerate()
                .find_map(|(i, (instr, _))| {
                    if let walrus::ir::Instr::Store(walrus::ir::Store {
                        kind: walrus::ir::StoreKind::I32_8 { atomic: false },
                        memory,
                        arg,
                    }) = instr
                    {
                        if *memory != ctx.vfs_used_memory_id.unwrap() {
                            return Some(Err(eyre::eyre!(
                                "Unexpected memory ID: expected {:?}, got {:?}",
                                ctx.vfs_used_memory_id.unwrap(),
                                *memory
                            )));
                        }
                        Some(Ok((i, arg.to_owned())))
                    } else {
                        None
                    }
                })
                .wrap_err_with(|| eyre::eyre!("Failed to find store instruction"))??;
            trap_body.remove(store_index + 1);
            trap_body.remove(store_index);
            trap_body.remove(store_index - 1);

            if let Some(id) = (
                UniqueName::NAMESPACE,
                &UniqueName::Memory(&MemoryUniqueName::MemoryDirector(wasm)),
            )
                .get_fid(&module.imports)
                .ok()
            {
                module
                    .replace_imported_func(id, |(builder, args)| {
                        let mut func_body = builder.func_body();
                        func_body
                            .local_get(args[0])
                            .call(trap_id)
                            .i32_const(store_info.offset as i32)
                            .binop(walrus::ir::BinaryOp::I32Add)
                            .return_();
                    })
                    .to_eyre()
                    .wrap_err_with(|| eyre::eyre!("Failed to replace imported function"))?;

                if ctx.unstable_print_debug {
                    module.exports.add(
                        &UniqueName::Memory(&MemoryUniqueName::MemoryDirectorAnchor(wasm))
                            .to_string(),
                        id,
                    );
                }
            }
        }

        Ok(())
    }
}