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. {mem:?}"
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
255        Ok(())
256    }
257
258    fn post_lower_memory(
259        &mut self,
260        module: &mut walrus::Module,
261        ctx: &GeneratorCtx,
262    ) -> eyre::Result<()> {
263        if !ctx.threads {
264            return Ok(());
265        }
266
267        if self.had_shared {
268            for mem in module.memories.iter_mut() {
269                mem.shared = true;
270            }
271        }
272
273        self.ready_component_and_transpile(module, ctx)?;
274
275        Ok(())
276    }
277
278    fn post_components(
279        &mut self,
280        module: &mut walrus::Module,
281        ctx: &ComponentCtx,
282    ) -> eyre::Result<()> {
283        if !ctx.threads() {
284            return Ok(());
285        }
286
287        self.memory_count = module
288            .load_info::<usize>("memory_count")
289            .wrap_err("Failed to load memory_count")?;
290
291        for count in 0..self.memory_count {
292            let (id, info) = module
293                .get_memory_anchor_with_info::<HadSharedAndImported>(
294                    &format!("__wasip1_vfs_memory_anchor_{count}"),
295                    true,
296                )
297                .wrap_err("cannot find info, you may change anchor name")?;
298            let info = info.unwrap();
299            let mem = module.memories.get_mut(id);
300
301            mem.name = info.name.clone();
302
303            if info.had_imported {
304                let import_id = module.imports.add(
305                    "env",
306                    &info.name.unwrap(),
307                    walrus::ImportKind::Memory(mem.id()),
308                );
309
310                mem.import = Some(import_id);
311            }
312            if info.had_shared {
313                mem.shared = true;
314            }
315        }
316
317        Ok(())
318    }
319}
320
321/// When exchanging data via Wasip1ABI,
322/// there are operations involving writing to
323/// and reading from memory.
324/// However, as these cannot be accessed during compilation,
325/// alternative functions are employed. These shall be replaced.
326///
327/// **Why this is needed:**
328/// Since the VFS layer needs to transfer data between its own memory and the guest's memory
329/// when processing ABI calls, it defines `memory_copy_from` and `memory_copy_to` as external imports.
330/// Since `walrus` does not allow generating components with unknown raw imports, this generator
331/// patches those structural import declarations with native `memory.copy` WebAssembly instructions
332/// executing over the correct `multi-memory` tables.
333#[derive(Debug, Default)]
334pub struct MemoryBridge;
335
336macro_rules! assert_ptr {
337    ($ptr:expr) => {
338        if { $ptr } != walrus::ValType::I32 {
339            let ptr = $ptr;
340            eyre::bail!("Invalid pointer type, expected i32. Got {ptr}");
341        }
342    };
343}
344
345macro_rules! assert_len {
346    ($len:expr) => {
347        if { $len } != walrus::ValType::I32 {
348            let len = $len;
349            eyre::bail!("Invalid length type, expected i32. Got {len}");
350        }
351    };
352}
353
354macro_rules! check_len {
355    ($params:expr, $len:expr) => {
356        if { $params.len() } != { $len } {
357            let len = $len;
358            eyre::bail!(
359                "Invalid params length, expected {len}. Got {}",
360                { $params }.len()
361            );
362        }
363    };
364}
365
366impl Generator for MemoryBridge {
367    fn post_combine(
368        &mut self,
369        module: &mut walrus::Module,
370        ctx: &GeneratorCtx,
371    ) -> eyre::Result<()> {
372        for wasm in &ctx.target_names {
373            let wasm_mem = ctx.target_used_memory_id.as_ref().unwrap()[wasm];
374            let vfs_mem = ctx.vfs_used_memory_id.unwrap();
375
376            if let Some(id) = (
377                UniqueName::NAMESPACE,
378                &UniqueName::Memory(&MemoryUniqueName::MemoryCopyFrom(wasm)),
379            )
380                .get_fid(&module.imports)
381                .ok()
382            {
383                let func = module.funcs.get(id);
384                let ty = module.types.get(func.ty());
385                let params = ty.params();
386
387                check_len!(params, 3);
388                assert_ptr!(params[0]); // offset
389                assert_ptr!(params[1]); // src
390                assert_len!(params[2]); // len
391                check_len!(ty.results(), 0);
392
393                module
394                    .replace_imported_func(id, |(body, args)| {
395                        body.local_get(args[0])
396                            .local_get(args[1])
397                            .local_get(args[2])
398                            .memory_copy(vfs_mem, wasm_mem);
399                    })
400                    .to_eyre()
401                    .wrap_err_with(|| eyre::eyre!("Failed to replace memory_copy_from"))?;
402            }
403
404            if let Some(id) = (
405                UniqueName::NAMESPACE,
406                &UniqueName::Memory(&MemoryUniqueName::MemoryCopyTo(wasm)),
407            )
408                .get_fid(&module.imports)
409                .ok()
410            {
411                let func = module.funcs.get(id);
412                let ty = module.types.get(func.ty());
413                let params = ty.params();
414
415                check_len!(params, 3);
416                assert_ptr!(params[0]); // offset
417                assert_ptr!(params[1]); // src
418                assert_len!(params[2]); // len
419                check_len!(ty.results(), 0);
420
421                module
422                    .replace_imported_func(id, |(body, args)| {
423                        body.local_get(args[0])
424                            .local_get(args[1])
425                            .local_get(args[2])
426                            .memory_copy(wasm_mem, vfs_mem);
427                    })
428                    .to_eyre()
429                    .wrap_err_with(|| eyre::eyre!("Failed to replace memory_copy_to"))?;
430            }
431        }
432
433        Ok(())
434    }
435}
436
437/// The final wasm, due to ABI constraints,
438/// only exposes vfs memory.
439/// Therefore, when calling the ABI from non-vfs memory,
440/// data must be copied. However,
441/// when ultimately consolidating memory into a single pool,
442/// data can be passed externally by directly passing pointers.
443/// To implement this optimization,
444/// a function is provided to determine the pointer bias
445/// before memory consolidation.
446///
447/// **Why this is needed:**
448/// If running in `single_memory` mode (without the `multi_memory` WASM feature), all modules'
449/// memories are merged into one large address space. The VFS needs to know where the guest
450/// module's memory segment actually resides within this merged pool. This generator uses a trap
451/// mechanism to securely determine the actual pointer bias at runtime so external callers and
452/// the VFS can translate addresses correctly.
453#[derive(Debug, Default)]
454pub struct MemoryTrap;
455
456impl Generator for MemoryTrap {
457    fn post_combine(
458        &mut self,
459        module: &mut walrus::Module,
460        ctx: &GeneratorCtx,
461    ) -> eyre::Result<()> {
462        if matches!(ctx.target_memory_type, TargetMemoryType::Multi) {
463            return Ok(());
464        }
465
466        for wasm in &ctx.target_names {
467            // NOTE: The import was created by the import_wasm! macro using the
468            // Rust identifier name (with underscores), but ctx.target_names has
469            // the package name (with dashes). We need to normalize to underscores
470            // to match what the macro generated.
471            let normalized_wasm = wasm.as_ref().replace('-', "_");
472            let import_name = format!("__wasip1_vfs_{normalized_wasm}_memory_trap");
473
474            if let Some(id) = (UniqueName::NAMESPACE, &import_name)
475                .get_fid(&module.imports)
476                .ok()
477            {
478                let func = module.funcs.get(id);
479                let ty = module.types.get(func.ty());
480                let params = ty.params();
481
482                check_len!(params, 1);
483                assert_ptr!(params[0]); // offset
484                check_len!(ty.results(), 1);
485                assert_ptr!(ty.results()[0]); // result
486
487                let wasm_mem = ctx.target_used_memory_id.as_ref().unwrap()[wasm];
488
489                module
490                    .replace_imported_func(id, |(body, args)| {
491                        body.local_get(args[0])
492                            .i32_const(0)
493                            .store(
494                                wasm_mem,
495                                ir::StoreKind::I32_8 { atomic: false },
496                                ir::MemArg {
497                                    align: 0,
498                                    offset: 0,
499                                },
500                            )
501                            .i32_const(0);
502                    })
503                    .to_eyre()
504                    .wrap_err_with(|| eyre::eyre!("Failed to replace memory_trap"))?;
505            }
506        }
507
508        Ok(())
509    }
510
511    fn post_lower_memory(
512        &mut self,
513        module: &mut walrus::Module,
514        ctx: &GeneratorCtx,
515    ) -> eyre::Result<()> {
516        if matches!(ctx.target_memory_type, TargetMemoryType::Multi) {
517            return Ok(());
518        }
519
520        for wasm in &ctx.target_names {
521            // NOTE: The export was created by the memory director macro using the
522            // Rust identifier name (with underscores), but ctx.target_names has
523            // the package name (with dashes). We need to normalize to underscores
524            // to match what the macro generated.
525            let normalized_wasm = wasm.as_ref().replace('-', "_");
526            let trap_export_name = format!("__wasip1_vfs_{normalized_wasm}_memory_trap_anchor");
527            let trap_id = trap_export_name
528                .get_fid(&module.exports)
529                .wrap_err_with(|| {
530                    eyre::eyre!("Failed to get {trap_export_name} export on {wasm}.")
531                })?;
532
533            module
534                .exports
535                .erase_with(trap_id, ctx.unstable_print_debug)?;
536
537            let trap_body = module.funcs.get_mut(trap_id).kind.unwrap_local_mut();
538            let trap_body = trap_body.block_mut(trap_body.entry_block());
539
540            // Remove the fake value instruction
541            // Optimization may have significantly altered the content,
542            // but I'll put it off for now.
543            let (store_index, store_info) = trap_body
544                .iter()
545                .enumerate()
546                .find_map(|(i, (instr, _))| {
547                    if let walrus::ir::Instr::Store(walrus::ir::Store {
548                        kind: walrus::ir::StoreKind::I32_8 { atomic: false },
549                        memory,
550                        arg,
551                    }) = instr
552                    {
553                        if *memory != ctx.vfs_used_memory_id.unwrap() {
554                            return Some(Err(eyre::eyre!(
555                                "Unexpected memory ID: expected {:?}, got {:?}",
556                                ctx.vfs_used_memory_id.unwrap(),
557                                *memory
558                            )));
559                        }
560                        Some(Ok((i, arg.to_owned())))
561                    } else {
562                        None
563                    }
564                })
565                .wrap_err_with(|| eyre::eyre!("Failed to find store instruction"))??;
566            trap_body.remove(store_index + 1);
567            trap_body.remove(store_index);
568            trap_body.remove(store_index - 1);
569
570            if let Some(id) = (
571                UniqueName::NAMESPACE,
572                &UniqueName::Memory(&MemoryUniqueName::MemoryDirector(wasm)),
573            )
574                .get_fid(&module.imports)
575                .ok()
576            {
577                module
578                    .replace_imported_func(id, |(builder, args)| {
579                        let mut func_body = builder.func_body();
580                        func_body
581                            .local_get(args[0])
582                            .call(trap_id)
583                            .i32_const(store_info.offset as i32)
584                            .binop(walrus::ir::BinaryOp::I32Add)
585                            .return_();
586                    })
587                    .to_eyre()
588                    .wrap_err_with(|| eyre::eyre!("Failed to replace imported function"))?;
589
590                if ctx.unstable_print_debug {
591                    module.exports.add(
592                        &UniqueName::Memory(&MemoryUniqueName::MemoryDirectorAnchor(wasm))
593                            .to_string(),
594                        id,
595                    );
596                }
597            }
598        }
599
600        Ok(())
601    }
602}