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