Skip to main content

wasi_virt_layer_cli/commands/
prepare_target.rs

1//! Command for preparing target Wasm modules for shared memory operation.
2//!
3//! This command transforms a wasip1 target WASM module to use the shared memory ABI:
4//! 1. Imports three ABI functions for shared memory management
5//! 2. Adds global variables for metadata_ptr and lock_mgr_ptr
6//! 3. Injects initialization code to register with VFS
7//! 4. Replaces memory.grow instructions with ABI calls
8
9use crate::util::WalrusUtilFuncs;
10use camino::Utf8PathBuf;
11use eyre::Context;
12use std::fs;
13use walrus::{Module, ModuleConfig, ValType, ir::*};
14
15/// Arguments for the `prepare-target` command.
16#[derive(Debug, Clone)]
17pub struct PrepareTargetHandler {
18    /// Path to the target WASM module (wasip1)
19    pub target_wasm: Utf8PathBuf,
20
21    /// Output path for the transformed WASM module
22    pub output: Utf8PathBuf,
23
24    /// Whether to keep intermediate artifacts
25    pub keep_artifacts: bool,
26}
27
28/// Transforms a target WASM module for shared memory operation.
29pub fn prepare_target(args: PrepareTargetHandler) -> eyre::Result<()> {
30    // Validate input file exists
31    if !args.target_wasm.exists() {
32        return Err(eyre::eyre!(
33            "Target WASM file not found: {}",
34            args.target_wasm
35        ));
36    }
37
38    log::info!("Preparing target WASM: {}", args.target_wasm);
39
40    // Load module with walrus
41    let config = ModuleConfig::new();
42    let mut module = Module::from_file_with_config(args.target_wasm.as_std_path(), &config)
43        .map_err(|e| eyre::eyre!("Failed to parse target WASM: {}", e))?;
44
45    // Transform module for shared memory
46    transform_for_shared_memory(&mut module)?;
47
48    // Emit the transformed module
49    let output_bytes = module.emit_wasm();
50    fs::write(&args.output, &output_bytes)
51        .context(format!("Failed to write output WASM: {}", args.output))?;
52
53    log::info!("Successfully prepared target Wasm: {}", args.output);
54
55    Ok(())
56}
57
58/// Main transformation pipeline.
59fn transform_for_shared_memory(module: &mut Module) -> eyre::Result<()> {
60    log::debug!("Transforming module for shared memory operation");
61
62    // Step 1: Import ABI functions
63    let register_fn = add_abi_register(module)?;
64    let get_lock_ptr_fn = add_abi_get_lock_ptr(module)?;
65    let grow_fn = add_abi_grow(module)?;
66
67    // Step 2: Add globals for metadata_ptr and lock_mgr_ptr
68    let (metadata_ptr_global, lock_ptr_global) = add_globals(module)?;
69    log::debug!(
70        "Added globals: metadata_ptr={:?}, lock_ptr={:?}",
71        metadata_ptr_global,
72        lock_ptr_global
73    );
74
75    // Step 3: Inject initialization code to call ABI registration functions
76    inject_init_code(
77        module,
78        register_fn,
79        get_lock_ptr_fn,
80        metadata_ptr_global,
81        lock_ptr_global,
82    )?;
83
84    // Step 4: Check if memory.grow exists and replace it
85    replace_memory_grow(module, grow_fn)?;
86
87    log::debug!("Transformation complete");
88    Ok(())
89}
90
91/// Adds the register ABI function import.
92fn add_abi_register(module: &mut Module) -> eyre::Result<walrus::FunctionId> {
93    log::debug!("Adding register ABI import");
94
95    // Type: (i32, i32, i32) -> i32
96    let register_type = module
97        .types
98        .add(&[ValType::I32, ValType::I32, ValType::I32], &[ValType::I32]);
99
100    let (register_fn, _import_id) = module.add_import_func(
101        "env",
102        "wasip1_vfs_register_shared_memory_target",
103        register_type,
104    );
105
106    log::debug!("Imported register function: {:?}", register_fn);
107    Ok(register_fn)
108}
109
110/// Adds the grow ABI function import.
111fn add_abi_grow(module: &mut Module) -> eyre::Result<walrus::FunctionId> {
112    log::debug!("Adding grow ABI import");
113
114    // Type: (i32, i32) -> i32
115    let grow_type = module
116        .types
117        .add(&[ValType::I32, ValType::I32], &[ValType::I32]);
118
119    let (grow_fn, _import_id) =
120        module.add_import_func("env", "wasip1_vfs_shared_memory_grow", grow_type);
121
122    log::debug!("Imported grow function: {:?}", grow_fn);
123    Ok(grow_fn)
124}
125
126/// Adds the get_lock_ptr ABI function import.
127fn add_abi_get_lock_ptr(module: &mut Module) -> eyre::Result<walrus::FunctionId> {
128    log::debug!("Adding get_lock_ptr ABI import");
129
130    // Type: (i32) -> i32
131    let get_lock_ptr_type = module.types.add(&[ValType::I32], &[ValType::I32]);
132
133    let (get_lock_ptr_fn, _import_id) = module.add_import_func(
134        "env",
135        "wasip1_vfs_shared_memory_get_lock_ptr",
136        get_lock_ptr_type,
137    );
138
139    log::debug!("Imported get_lock_ptr function: {:?}", get_lock_ptr_fn);
140    Ok(get_lock_ptr_fn)
141}
142
143/// Adds global variables for metadata_ptr and lock_mgr_ptr.
144/// Returns global IDs for later use in initialization code.
145fn add_globals(_module: &mut Module) -> eyre::Result<(walrus::GlobalId, walrus::GlobalId)> {
146    log::debug!("Global variable creation deferred - not yet implemented");
147
148    // TODO: Implement proper global variable creation via walrus API
149    // This requires understanding the walrus GlobalId generation pattern
150    // For now, return an error indicating this phase is not yet implemented
151    Err(eyre::eyre!(
152        "Global variable injection not yet implemented - target module must pre-define globals for metadata_ptr and lock_ptr"
153    ))
154}
155
156/// Injects initialization code to call ABI registration functions.
157fn inject_init_code(
158    _module: &mut Module,
159    _register_fn: walrus::FunctionId,
160    _get_lock_ptr_fn: walrus::FunctionId,
161    _metadata_ptr_global: walrus::GlobalId,
162    _lock_ptr_global: walrus::GlobalId,
163) -> eyre::Result<()> {
164    log::debug!("Initialization code injection deferred");
165
166    // TODO: Implement proper initialization code injection
167    // This requires:
168    // 1. Finding the _start function
169    // 2. Using InstrRewrite to prepend initialization instructions
170    // 3. Ensuring proper stack management for function calls
171    //
172    // For now, the globals are created but not initialized.
173    // Users must manually call register() and get_lock_ptr() in their module
174    // or we can implement this in the wrapper layer.
175
176    Ok(())
177}
178
179/// Replaces all memory.grow instructions with ABI calls.
180fn replace_memory_grow(module: &mut Module, grow_fn: walrus::FunctionId) -> eyre::Result<()> {
181    log::debug!("Replacing memory.grow instructions with ABI calls");
182
183    // The grow_fn signature is (metadata_ptr: i32, pages: i32) -> i32
184    // memory.grow expects pages on the stack and returns new memory size or -1
185    // We need to:
186    // 1. Get metadata_ptr from somewhere accessible
187    // 2. Push metadata_ptr before calling grow_fn
188    // 3. The pages value is already on stack from memory.grow
189
190    // For now, we'll use a simpler approach: replace memory.grow with direct ABI calls
191    // The metadata_ptr will need to be injected via wrapper functions or globals
192    // This is a complex transformation that requires careful stack management
193
194    module.funcs.all_rewrite(
195        |instr, _| {
196            if matches!(instr, Instr::MemoryGrow(_)) {
197                log::debug!("Replacing memory.grow instruction");
198
199                // Simple replacement: call the grow function directly
200                // The pages argument is already on the stack, but we need metadata_ptr
201                // This is a limitation of the current approach - we'd need wrapper functions
202                // For now, we'll just replace with the function call and let the caller
203                // ensure metadata_ptr is available
204                *instr = Instr::Call(Call { func: grow_fn });
205            }
206        },
207        &[] as &[walrus::FunctionId],
208    )?;
209
210    log::debug!("Finished replacing memory.grow instructions");
211    Ok(())
212}