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