Skip to main content

wasi_virt_layer_cli/generator/
start_section.rs

1use std::collections::HashMap;
2use std::panic;
3use std::sync::Arc;
4use walrus::FunctionId;
5
6use crate::{
7    generator::{Generator, GeneratorCtx},
8    unique_name::UniqueName,
9    util::{WalrusFID, WasmName},
10};
11
12/// Dictates the execution phase for added start functions.
13#[derive(Debug, Clone)]
14pub enum StartFnPriority {
15    /// Evaluated aggressively right after resetting the memory module.
16    AfterMemoryReset,
17    /// Highest priority, placed right before finalizing processing.
18    AfterAll,
19}
20
21/// Aggregates priority and source information for a start function.
22#[derive(Debug)]
23pub struct StartFnInfo {
24    /// Priority of this start evaluation logic.
25    pub priority: StartFnPriority,
26    /// Generational strategy mapping for initializing source routines.
27    pub source: StartSource,
28}
29
30/// Specifies how the start function should be provided or rewritten.
31pub enum StartSource {
32    /// Targets an existing exported function.
33    ExportFunc(String),
34    /// Represents an internal rewriting closure applied sequentially.
35    Rewrite(Option<Box<dyn FnOnce(&mut walrus::Module, &GeneratorCtx) -> eyre::Result<()>>>),
36}
37
38impl core::fmt::Debug for StartSource {
39    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
40        match self {
41            StartSource::ExportFunc(name) => {
42                write!(f, "ExportFunc({})", name)
43            }
44            StartSource::Rewrite(_) => {
45                write!(f, "Rewrite(<function>)")
46            }
47        }
48    }
49}
50
51#[derive(Debug, Clone, strum::AsRefStr, strum::EnumCount, PartialEq, Eq, Hash)]
52#[strum(serialize_all = "snake_case")]
53/// Alternatives internally tracked to swap initial execution targets safely.
54pub enum StartAlternativeName {
55    /// Initialize each target wasm module
56    WasmName(WasmName),
57    /// This is the VFS initialization function
58    VFS(WasmName),
59    /// This should call after resetting the memory state
60    /// Conclusion: All initialization function must be done here
61    AfterMemoryReset,
62}
63
64/// Common mutable state shared across the start section generator and builder.
65#[derive(Debug, Default)]
66pub struct StartSectionCommon {
67    /// Additional start functions.
68    map: Vec<StartFnInfo>,
69    /// The function body is an import fn and is replaced during the Build phase.
70    start_alternatives: HashMap<StartAlternativeName, FunctionId>,
71    is_builded: bool,
72}
73
74impl StartSectionCommon {
75    /// Retrieves the function ID assigned for the VFS start component.
76    pub fn vfs_start_fid(&self) -> (WasmName, FunctionId) {
77        self.start_alternatives
78            .iter()
79            .find_map(|(name, fid)| match name {
80                StartAlternativeName::VFS(wasm_name) => Some((wasm_name.clone(), *fid)),
81                _ => None,
82            })
83            .expect("VFS start alternative must exist")
84    }
85
86    /// Iterates over all start alternatives and their resolved function IDs.
87    pub fn iter(&self) -> impl Iterator<Item = (&StartAlternativeName, FunctionId)> {
88        self.start_alternatives.iter().map(|(a, b)| (a, *b))
89    }
90
91    /// Returns function IDs for the target WebAssembly module initializations.
92    pub fn target_wasm_fids(&self) -> impl Iterator<Item = (&WasmName, FunctionId)> {
93        self.start_alternatives
94            .iter()
95            .filter_map(move |(name, fid)| match name {
96                StartAlternativeName::WasmName(wasm_name) => Some((wasm_name, *fid)),
97                _ => None,
98            })
99    }
100
101    /// Verifies that the start section has not already been built.
102    pub fn check_is_builded(&self) {
103        if self.is_builded {
104            panic!("StartSectionCommon has already been built");
105        }
106    }
107}
108
109/// Generator responsible for replacing the Wasm start section.
110#[derive(Debug, Default)]
111pub struct StartSectionGenerator {
112    common: Option<Arc<parking_lot::Mutex<StartSectionCommon>>>,
113}
114
115impl StartSectionGenerator {
116    /// Initializes the generator with required placeholders and state.
117    pub fn init(
118        &mut self,
119        module: &mut walrus::Module,
120        vfs_name: WasmName,
121        wasm_names: &[WasmName],
122    ) {
123        if let Some(_) = &self.common {
124            // let mut common = common.lock();
125            // common.start_alternatives.clear();
126            // for name in wasm_names {
127            //     let unique_name = Self::unique_import_name(name);
128            //     // if (UniqueName::NAMESPACE, &unique_name).get_fid(&module.imports).is_ok() {
129            //     //     panic!("Import function for start alternative '{name}' already exists");
130            //     // }
131            //     let fid = (UniqueName::NAMESPACE, &unique_name)
132            //         .get_fid(&module.imports)
133            //         .unwrap_or_else(|_| {
134            //             let func_ty = module.types.add(&[], &[]);
135            //             let (new_fid, _) = module.add_import_func(UniqueName::NAMESPACE, &unique_name, func_ty);
136            //             new_fid
137            //         });
138            //     common.start_alternatives.insert(name.clone(), fid);
139            // }
140            panic!("Re-initialization of StartSectionGenerator is not supported");
141        } else {
142            let func_ty = module.types.add(&[], &[]);
143            let common = StartSectionCommon {
144                map: Vec::new(),
145                is_builded: false,
146                start_alternatives: core::iter::once(StartAlternativeName::VFS(vfs_name.clone()))
147                    .chain(core::iter::once(StartAlternativeName::AfterMemoryReset))
148                    .chain(
149                        wasm_names
150                            .iter()
151                            .cloned()
152                            .map(StartAlternativeName::WasmName),
153                    )
154                    .map(|name| {
155                        let unique_name = UniqueName::StartAlternative(&name);
156                        if (UniqueName::NAMESPACE, &unique_name)
157                            .get_fid(&module.imports)
158                            .is_ok()
159                        {
160                            panic!(
161                                "Import function for start alternative '{name:?}' already exists"
162                            );
163                        }
164                        let (new_fid, _) = module.add_import_func(
165                            UniqueName::NAMESPACE,
166                            &unique_name.to_string(),
167                            func_ty,
168                        );
169                        (name, new_fid)
170                    })
171                    .collect(),
172            };
173            self.common = Some(Arc::new(parking_lot::Mutex::new(common)));
174        }
175    }
176
177    /// Spawns a builder object to enqueue hooks and references.
178    pub fn builder(&self) -> StartSectionBuilder {
179        match &self.common {
180            None => panic!("StartSectionGenerator is not initialized"),
181            Some(common) => {
182                if common.lock().is_builded {
183                    panic!("StartSectionGenerator has already been built");
184                }
185            }
186        }
187
188        StartSectionBuilder {
189            common: self.common.as_ref().unwrap().clone(),
190        }
191    }
192
193    /// Finalizes the start sequence replacement within the designated Wasm module.
194    pub fn build(self, module: &mut walrus::Module, ctx: &GeneratorCtx) -> eyre::Result<()> {
195        let common = self.common.unwrap();
196        let mut common = common.lock();
197        common.is_builded = true;
198
199        // todo!();
200
201        for info in common
202            .map
203            .iter_mut()
204            .filter(|info| matches!(info.priority, StartFnPriority::AfterAll))
205        {
206            match &mut info.source {
207                StartSource::ExportFunc(_name) => {
208                    unimplemented!();
209                }
210                StartSource::Rewrite(f) => {
211                    if let Some(f) = f.take() {
212                        f(module, ctx)?;
213                    } else {
214                        panic!("StartSource::Rewrite function has already been taken");
215                    }
216                }
217            }
218        }
219
220        Ok(())
221    }
222}
223
224impl Generator for StartSectionGenerator {}
225
226/// Shared reference builder for managing initialization hooks safely.
227#[derive(Debug, Clone)]
228pub struct StartSectionBuilder {
229    common: Arc<parking_lot::Mutex<StartSectionCommon>>,
230}
231
232impl StartSectionBuilder {
233    /// Iterates through collected start alternative bindings.
234    pub fn iter(&self) -> Vec<(StartAlternativeName, FunctionId)> {
235        self.common
236            .lock()
237            .start_alternatives
238            .iter()
239            .map(|(name, fid)| (name.clone(), *fid))
240            .collect::<Vec<_>>()
241    }
242
243    /// Fetches the ID mapped to the main VFS initialization function.
244    pub fn vfs_start_fid(&self) -> (WasmName, FunctionId) {
245        self.common.lock().vfs_start_fid()
246    }
247
248    /// Returns the FID assigned for execution after memory resets flow.
249    pub fn after_memory_reset_fid(&self) -> FunctionId {
250        self.common
251            .lock()
252            .start_alternatives
253            .get(&StartAlternativeName::AfterMemoryReset)
254            .copied()
255            .expect("AfterMemoryReset start alternative must exist")
256    }
257
258    /// Retrieves registered function IDs designated to target specific Wasm scopes.
259    pub fn target_wasm_fids(&self) -> Vec<(WasmName, FunctionId)> {
260        self.common
261            .lock()
262            .target_wasm_fids()
263            .map(|(name, fid)| (name.clone(), fid))
264            .collect::<Vec<_>>()
265    }
266
267    /// Enqueues an additional start function for the final module load phase.
268    pub fn add_start_fn(&self, info: StartFnInfo) {
269        self.common.lock().check_is_builded();
270
271        self.common.lock().map.push(info);
272    }
273}