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