Skip to main content

wasi_virt_layer_cli/generator/
memory.rs

1use std::{collections::HashMap, str::FromStr};
2
3use eyre::{Context as _, ContextCompat as _};
4use walrus::ir;
5
6use crate::{
7    args::TargetMemoryType,
8    generator::{ComponentCtx, Generator, GeneratorCtx},
9    unique_name::UniqueName,
10    util::{ResultUtil as _, WalrusFID, WalrusUtilExport, WalrusUtilModule, WasmName},
11};
12
13/// Encapsulates naming variants reserved for VFS memory interactions.
14#[derive(Debug, strum::AsRefStr, strum::EnumCount, Hash, PartialEq, Eq, strum::VariantNames)]
15#[strum(serialize_all = "snake_case")]
16pub enum MemoryUniqueName<'a> {
17    /// Copies contents from Target Memory to VFS Memory.
18    MemoryCopyFrom(&'a WasmName),
19    /// Copies contents from VFS Memory to Target Memory.
20    MemoryCopyTo(&'a WasmName),
21    /// Emplaces a runtime trap to deduce pointer arithmetic limits.
22    MemoryTrap(&'a WasmName),
23    /// Serves as a linked anchor ensuring `MemoryTrap` preserves its compiled identity.
24    MemoryTrapAnchor(&'a WasmName),
25    /// Wraps dynamic function dispatch controlling pointers to merged targets.
26    MemoryDirector(&'a WasmName),
27    /// Serves as a linked anchor preserving the compiled `MemoryDirector` identity.
28    MemoryDirectorAnchor(&'a WasmName),
29    /// The fundamental reference identifying the exported memory location of the underlying module.
30    Memory(&'a WasmName),
31}
32
33/// ABI Generator: Manages memory configurations temporarily during transpilation.
34///
35/// **Why this is needed:**
36/// Certain WebAssembly translating/optimizing tools cannot handle shared memory or multiple memories
37/// if threading features are disabled or unavailable in the environment. This generator temporarily
38/// unshares imported memory, performs the component transformations, and then properly re-links
39/// or re-shares the memory so the VFS has correct access to the target modules' structures.
40#[derive(Debug, Default)]
41pub struct TemporaryRefugeMemory {
42    /// Indicates the overall tracked quantity of memory blocks actively transpiled.
43    pub memory_count: usize,
44    /// Indicates if any memory had the shared flag set before multi-memory-lowering.
45    pub had_shared: bool,
46}
47
48impl TemporaryRefugeMemory {
49    /// Standardizes the component structure and ensures temporary threading parameters accommodate memory translations.
50    pub fn ready_component_and_transpile(
51        &mut self,
52        module: &mut walrus::Module,
53        _ctx: &GeneratorCtx,
54    ) -> eyre::Result<()> {
55        let mut is_first = false;
56
57        let mut imported_memories = Vec::new();
58        let mut shared_memories = Vec::new();
59
60        let mut mem_names = HashMap::new();
61
62        module
63            .memories
64            .iter_mut()
65            .map(|mem| {
66                let id = mem.id();
67
68                if let Some(mem_id) = mem.import {
69                    imported_memories.push(id);
70                    let import = module.imports.get(mem_id);
71                    let name = import.name.clone();
72                    module.imports.delete(mem_id);
73                    mem.import = None;
74                    if mem_names.values().any(|s| *s == name) {
75                        let n = (1..)
76                            .find(|n| !mem_names.values().any(|s| *s == format!("{name}_{n}")))
77                            .unwrap();
78                        mem_names.insert(id, format!("{name}_{n}"));
79                    } else {
80                        mem_names.insert(id, name);
81                    }
82                }
83
84                // Translating component requires WasmFeatures::Threads
85                // but we cannot enable it because it in other crates.
86                // So, we set shared to false here temporarily.
87                if mem.shared {
88                    if !is_first {
89                        is_first = true;
90                        log::warn!(
91                            r"Transpiling with threads is not supported yet. so this wasm off memory shared flag and can't be used as it is."
92                        );
93                    }
94
95                    shared_memories.push(id);
96                    mem.shared = false;
97                }
98
99                Ok(())
100            })
101            .collect::<eyre::Result<Vec<_>>>()?;
102
103        for (n, mem_id) in module
104            .memories
105            .iter()
106            .map(|mem| mem.id())
107            .enumerate()
108            .collect::<Box<_>>()
109        {
110            module.create_memory_anchor_with_info(
111                format!("__wasip1_vfs_memory_anchor_{n}"),
112                mem_id,
113                Some(HadSharedAndImported {
114                    had_shared: shared_memories.contains(&mem_id),
115                    had_imported: imported_memories.contains(&mem_id),
116                    name: mem_names.get(&mem_id).cloned(),
117                }),
118            )?;
119        }
120
121        self.memory_count = module.memories.iter().count();
122
123        module
124            .save_info("memory_count", self.memory_count)
125            .wrap_err("Failed to save memory_count")?;
126
127        Ok(())
128    }
129}
130
131#[derive(Debug, Clone)]
132struct HadSharedAndImported {
133    pub had_shared: bool,
134    pub had_imported: bool,
135    pub name: Option<String>,
136}
137
138impl ToString for HadSharedAndImported {
139    fn to_string(&self) -> String {
140        let n = self.had_shared as u8
141            | (self.had_imported as u8) << 1
142            | (self.name.is_some() as u8) << 2;
143        format!("{n}{}", self.name.as_ref().unwrap_or(&"".into()))
144    }
145}
146
147impl FromStr for HadSharedAndImported {
148    type Err = eyre::Report;
149
150    fn from_str(s: &str) -> Result<Self, Self::Err> {
151        let n = s[0..1]
152            .parse::<u8>()
153            .wrap_err_with(|| eyre::eyre!("Failed to parse HadSharedAndImported from {s}"))?;
154        let name = if n & 4 != 0 {
155            Some(s[1..].to_string())
156        } else {
157            None
158        };
159        Ok(Self {
160            had_shared: (n & 1) != 0,
161            had_imported: (n & 2) != 0,
162            name,
163        })
164    }
165}
166
167impl Generator for TemporaryRefugeMemory {
168    fn pre_target(
169        &mut self,
170        module: &mut walrus::Module,
171        _: &GeneratorCtx,
172        external: &crate::generator::ModuleExternal,
173    ) -> eyre::Result<()> {
174        module
175            .exports
176            .iter_mut()
177            .find(|export| export.name == "memory")
178            .unwrap()
179            .name = UniqueName::Memory(&MemoryUniqueName::Memory(&external.name)).to_string();
180
181        Ok(())
182    }
183
184    fn post_combine(
185        &mut self,
186        module: &mut walrus::Module,
187        ctx: &GeneratorCtx,
188    ) -> eyre::Result<()> {
189        // Remove memory exports outside of VFS.
190        // Connect all non-VFS ABIs to VFS and hide them.
191        let mem_export_id = module
192            .exports
193            .iter()
194            .filter(|export|
195                matches!(export.item, walrus::ExportItem::Memory(mem) if ctx.vfs_used_memory_id.as_ref().unwrap() != &mem)
196            )
197            .map(|export| export.id())
198            .collect::<Vec<_>>();
199
200        for id in mem_export_id {
201            module.exports.delete(id);
202        }
203
204        // rename vfs memory export to memory
205        module
206            .memories
207            .get_mut(ctx.vfs_used_memory_id.unwrap())
208            .name = Some("memory".to_string());
209        module
210            .exports
211            .get_mut(
212                module
213                    .exports
214                    .get_exported_memory(ctx.vfs_used_memory_id.unwrap())
215                    .unwrap()
216                    .id(),
217            )
218            .name = "memory".to_string();
219
220        if !ctx.threads {
221            return Ok(());
222        }
223
224        if ctx.target_memory_type == TargetMemoryType::Multi {
225            self.ready_component_and_transpile(module, ctx)?;
226        } else {
227            for mem in module.memories.iter_mut() {
228                if mem.shared {
229                    self.had_shared = true;
230                    mem.shared = false;
231                }
232            }
233
234            module
235                .memories
236                .iter_mut()
237                .filter(|mem| mem.id() != *ctx.vfs_used_memory_id.as_ref().unwrap())
238                .map(|mem| {
239                    let id = mem.id();
240                    let mem_id = module.imports.iter().find_map(|import| match import.kind {
241                        walrus::ImportKind::Memory(mid) if mid == id => Some(import.id()),
242                        _ => None,
243                    });
244
245                    if let Some(mem_id) = mem_id {
246                        module.imports.delete(mem_id);
247                        mem.import = None;
248                    }
249
250                    Ok(())
251                })
252                .collect::<eyre::Result<Vec<_>>>()?;
253
254            // import vfs memory
255            // For lowering with wasm-opt,
256            // the VFS memory must be placed at index 0.
257            // Due to the way Walrus works, importing only this will place it at index 0.
258            match module.memories.iter().filter(|mem| mem.id() == ctx.vfs_used_memory_id.unwrap()).filter(|mem| mem.import.is_some()).count() {
259                0 => {
260                    let mem = module.memories.get_mut(ctx.vfs_used_memory_id.unwrap());
261                    let import_id = module.imports.add(
262                        "env",
263                        "memory",
264                        walrus::ImportKind::Memory(mem.id()),
265                    );
266                    mem.import = Some(import_id);
267                },
268                1 => {},
269                _ => panic!("VFS memory should be imported exactly once"),
270            }
271        }
272
273        Ok(())
274    }
275
276    fn post_lower_memory(
277        &mut self,
278        module: &mut walrus::Module,
279        ctx: &GeneratorCtx,
280    ) -> eyre::Result<()> {
281        if !ctx.threads {
282            return Ok(());
283        }
284
285        if self.had_shared {
286            for mem in module.memories.iter_mut() {
287                mem.shared = true;
288            }
289        }
290
291        self.ready_component_and_transpile(module, ctx)?;
292
293        Ok(())
294    }
295
296    fn post_components(
297        &mut self,
298        module: &mut walrus::Module,
299        ctx: &ComponentCtx,
300    ) -> eyre::Result<()> {
301        if !ctx.threads() {
302            return Ok(());
303        }
304
305        self.memory_count = module
306            .load_info::<usize>("memory_count")
307            .wrap_err("Failed to load memory_count")?;
308
309        for count in 0..self.memory_count {
310            let (id, info) = module
311                .get_memory_anchor_with_info::<HadSharedAndImported>(
312                    &format!("__wasip1_vfs_memory_anchor_{count}"),
313                    true,
314                )
315                .wrap_err("cannot find info, you may change anchor name")?;
316            let info = info.unwrap();
317            let mem = module.memories.get_mut(id);
318
319            mem.name = info.name.clone();
320
321            if info.had_imported {
322                let import_id = module.imports.add(
323                    "env",
324                    &info.name.unwrap(),
325                    walrus::ImportKind::Memory(mem.id()),
326                );
327
328                mem.import = Some(import_id);
329            }
330            if info.had_shared {
331                mem.shared = true;
332            }
333        }
334
335        Ok(())
336    }
337}
338
339/// When exchanging data via Wasip1ABI,
340/// there are operations involving writing to
341/// and reading from memory.
342/// However, as these cannot be accessed during compilation,
343/// alternative functions are employed. These shall be replaced.
344///
345/// **Why this is needed:**
346/// Since the VFS layer needs to transfer data between its own memory and the guest's memory
347/// when processing ABI calls, it defines `memory_copy_from` and `memory_copy_to` as external imports.
348/// Since `walrus` does not allow generating components with unknown raw imports, this generator
349/// patches those structural import declarations with native `memory.copy` WebAssembly instructions
350/// executing over the correct `multi-memory` tables.
351#[derive(Debug, Default)]
352pub struct MemoryBridge;
353
354macro_rules! assert_ptr {
355    ($ptr:expr) => {
356        if { $ptr } != walrus::ValType::I32 {
357            let ptr = $ptr;
358            eyre::bail!("Invalid pointer type, expected i32. Got {ptr}");
359        }
360    };
361}
362
363macro_rules! assert_len {
364    ($len:expr) => {
365        if { $len } != walrus::ValType::I32 {
366            let len = $len;
367            eyre::bail!("Invalid length type, expected i32. Got {len}");
368        }
369    };
370}
371
372macro_rules! check_len {
373    ($params:expr, $len:expr) => {
374        if { $params.len() } != { $len } {
375            let len = $len;
376            eyre::bail!(
377                "Invalid params length, expected {len}. Got {}",
378                { $params }.len()
379            );
380        }
381    };
382}
383
384impl Generator for MemoryBridge {
385    fn post_combine(
386        &mut self,
387        module: &mut walrus::Module,
388        ctx: &GeneratorCtx,
389    ) -> eyre::Result<()> {
390        for wasm in &ctx.target_names {
391            let wasm_mem = ctx.target_used_memory_id.as_ref().unwrap()[wasm];
392            let vfs_mem = ctx.vfs_used_memory_id.unwrap();
393
394            if let Some(id) = (
395                UniqueName::NAMESPACE,
396                &UniqueName::Memory(&MemoryUniqueName::MemoryCopyFrom(wasm)),
397            )
398                .get_fid(&module.imports)
399                .ok()
400            {
401                let func = module.funcs.get(id);
402                let ty = module.types.get(func.ty());
403                let params = ty.params();
404
405                check_len!(params, 3);
406                assert_ptr!(params[0]); // offset
407                assert_ptr!(params[1]); // src
408                assert_len!(params[2]); // len
409                check_len!(ty.results(), 0);
410
411                module
412                    .replace_imported_func(id, |(body, args)| {
413                        body.local_get(args[0])
414                            .local_get(args[1])
415                            .local_get(args[2])
416                            .memory_copy(vfs_mem, wasm_mem);
417                    })
418                    .to_eyre()
419                    .wrap_err_with(|| eyre::eyre!("Failed to replace memory_copy_from"))?;
420            }
421
422            if let Some(id) = (
423                UniqueName::NAMESPACE,
424                &UniqueName::Memory(&MemoryUniqueName::MemoryCopyTo(wasm)),
425            )
426                .get_fid(&module.imports)
427                .ok()
428            {
429                let func = module.funcs.get(id);
430                let ty = module.types.get(func.ty());
431                let params = ty.params();
432
433                check_len!(params, 3);
434                assert_ptr!(params[0]); // offset
435                assert_ptr!(params[1]); // src
436                assert_len!(params[2]); // len
437                check_len!(ty.results(), 0);
438
439                module
440                    .replace_imported_func(id, |(body, args)| {
441                        body.local_get(args[0])
442                            .local_get(args[1])
443                            .local_get(args[2])
444                            .memory_copy(wasm_mem, vfs_mem);
445                    })
446                    .to_eyre()
447                    .wrap_err_with(|| eyre::eyre!("Failed to replace memory_copy_to"))?;
448            }
449        }
450
451        Ok(())
452    }
453}
454
455/// The final wasm, due to ABI constraints,
456/// only exposes vfs memory.
457/// Therefore, when calling the ABI from non-vfs memory,
458/// data must be copied. However,
459/// when ultimately consolidating memory into a single pool,
460/// data can be passed externally by directly passing pointers.
461/// To implement this optimization,
462/// a function is provided to determine the pointer bias
463/// before memory consolidation.
464///
465/// **Why this is needed:**
466/// If running in `single_memory` mode (without the `multi_memory` WASM feature), all modules'
467/// memories are merged into one large address space. The VFS needs to know where the guest
468/// module's memory segment actually resides within this merged pool. This generator uses a trap
469/// mechanism to securely determine the actual pointer bias at runtime so external callers and
470/// the VFS can translate addresses correctly.
471#[derive(Debug, Default)]
472pub struct MemoryTrap;
473
474impl Generator for MemoryTrap {
475    fn post_combine(
476        &mut self,
477        module: &mut walrus::Module,
478        ctx: &GeneratorCtx,
479    ) -> eyre::Result<()> {
480        if matches!(ctx.target_memory_type, TargetMemoryType::Multi) {
481            return Ok(());
482        }
483
484        for wasm in &ctx.target_names {
485            // NOTE: The import was created by the import_wasm! macro using the
486            // Rust identifier name (with underscores), but ctx.target_names has
487            // the package name (with dashes). We need to normalize to underscores
488            // to match what the macro generated.
489            let normalized_wasm = wasm.as_ref().replace('-', "_");
490            let import_name = format!("__wasip1_vfs_{normalized_wasm}_memory_trap");
491
492            if let Some(id) = (UniqueName::NAMESPACE, &import_name)
493                .get_fid(&module.imports)
494                .ok()
495            {
496                let func = module.funcs.get(id);
497                let ty = module.types.get(func.ty());
498                let params = ty.params();
499
500                check_len!(params, 1);
501                assert_ptr!(params[0]); // offset
502                check_len!(ty.results(), 1);
503                assert_ptr!(ty.results()[0]); // result
504
505                let wasm_mem = ctx.target_used_memory_id.as_ref().unwrap()[wasm];
506
507                module
508                    .replace_imported_func(id, |(body, args)| {
509                        body.local_get(args[0])
510                            .i32_const(0)
511                            .store(
512                                wasm_mem,
513                                ir::StoreKind::I32_8 { atomic: false },
514                                ir::MemArg {
515                                    align: 0,
516                                    offset: 0,
517                                },
518                            )
519                            .i32_const(0);
520                    })
521                    .to_eyre()
522                    .wrap_err_with(|| eyre::eyre!("Failed to replace memory_trap"))?;
523            }
524        }
525
526        Ok(())
527    }
528
529    fn post_lower_memory(
530        &mut self,
531        module: &mut walrus::Module,
532        ctx: &GeneratorCtx,
533    ) -> eyre::Result<()> {
534        if matches!(ctx.target_memory_type, TargetMemoryType::Multi) {
535            return Ok(());
536        }
537
538        for wasm in &ctx.target_names {
539            // NOTE: The export was created by the memory director macro using the
540            // Rust identifier name (with underscores), but ctx.target_names has
541            // the package name (with dashes). We need to normalize to underscores
542            // to match what the macro generated.
543            let normalized_wasm = wasm.as_ref().replace('-', "_");
544            let trap_export_name = format!("__wasip1_vfs_{normalized_wasm}_memory_trap_anchor");
545            let trap_id = trap_export_name
546                .get_fid(&module.exports)
547                .wrap_err_with(|| {
548                    eyre::eyre!("Failed to get {trap_export_name} export on {wasm}.")
549                })?;
550
551            module
552                .exports
553                .erase_with(trap_id, ctx.unstable_print_debug)?;
554
555            let trap_body = module.funcs.get_mut(trap_id).kind.unwrap_local_mut();
556            let trap_body = trap_body.block_mut(trap_body.entry_block());
557
558            // Remove the fake value instruction
559            // Optimization may have significantly altered the content,
560            // but I'll put it off for now.
561            let (store_index, store_info) = trap_body
562                .iter()
563                .enumerate()
564                .find_map(|(i, (instr, _))| {
565                    if let walrus::ir::Instr::Store(walrus::ir::Store {
566                        kind: walrus::ir::StoreKind::I32_8 { atomic: false },
567                        memory,
568                        arg,
569                    }) = instr
570                    {
571                        if *memory != ctx.vfs_used_memory_id.unwrap() {
572                            return Some(Err(eyre::eyre!(
573                                "Unexpected memory ID: expected {:?}, got {:?}",
574                                ctx.vfs_used_memory_id.unwrap(),
575                                *memory
576                            )));
577                        }
578                        Some(Ok((i, arg.to_owned())))
579                    } else {
580                        None
581                    }
582                })
583                .wrap_err_with(|| eyre::eyre!("Failed to find store instruction"))??;
584            trap_body.remove(store_index + 1);
585            trap_body.remove(store_index);
586            trap_body.remove(store_index - 1);
587
588            if let Some(id) = (
589                UniqueName::NAMESPACE,
590                &UniqueName::Memory(&MemoryUniqueName::MemoryDirector(wasm)),
591            )
592                .get_fid(&module.imports)
593                .ok()
594            {
595                module
596                    .replace_imported_func(id, |(builder, args)| {
597                        let mut func_body = builder.func_body();
598                        func_body
599                            .local_get(args[0])
600                            .call(trap_id)
601                            .i32_const(store_info.offset as i32)
602                            .binop(walrus::ir::BinaryOp::I32Add)
603                            .return_();
604                    })
605                    .to_eyre()
606                    .wrap_err_with(|| eyre::eyre!("Failed to replace imported function"))?;
607
608                if ctx.unstable_print_debug {
609                    module.exports.add(
610                        &UniqueName::Memory(&MemoryUniqueName::MemoryDirectorAnchor(wasm))
611                            .to_string(),
612                        id,
613                    );
614                }
615            }
616        }
617
618        Ok(())
619    }
620}