Skip to main content

wasi_virt_layer_cli/generator/
start_section.rs

1use itertools::Itertools;
2use std::collections::HashMap;
3use std::panic;
4use std::sync::Arc;
5use walrus::FunctionId;
6
7use crate::{
8    generator::{Generator, GeneratorCtx},
9    unique_name::UniqueName,
10    util::{WalrusFID, WalrusUtilExport, WalrusUtilFuncs, WalrusUtilModule, WasmName},
11};
12
13#[derive(Debug, Clone)]
14pub enum StartFnPriority {
15    AfterMemoryReset,
16    AfterAll,
17}
18
19#[derive(Debug)]
20pub struct StartFnInfo {
21    pub priority: StartFnPriority,
22    pub source: StartSource,
23}
24
25pub enum StartSource {
26    ExportFunc(String),
27    Rewrite(Option<Box<dyn FnOnce(&mut walrus::Module, &GeneratorCtx) -> eyre::Result<()>>>),
28}
29
30impl core::fmt::Debug for StartSource {
31    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
32        match self {
33            StartSource::ExportFunc(name) => {
34                write!(f, "ExportFunc({})", name)
35            }
36            StartSource::Rewrite(_) => {
37                write!(f, "Rewrite(<function>)")
38            }
39        }
40    }
41}
42
43#[derive(Debug, Clone, strum::AsRefStr, strum::EnumCount, PartialEq, Eq, Hash)]
44#[strum(serialize_all = "snake_case")]
45pub enum StartAlternativeName {
46    /// Initialize each target wasm module
47    WasmName(WasmName),
48    /// This is the VFS initialization function
49    VFS(WasmName),
50    /// This should call after resetting the memory state
51    /// Conclusion: All initialization function must be done here
52    AfterMemoryReset,
53}
54
55#[derive(Debug, Default)]
56pub struct StartSectionCommon {
57    /// Additional start functions.
58    map: Vec<StartFnInfo>,
59    /// The function body is an import fn and is replaced during the Build phase.
60    start_alternatives: HashMap<StartAlternativeName, FunctionId>,
61    is_builded: bool,
62}
63
64impl StartSectionCommon {
65    pub fn vfs_start_fid(&self) -> (WasmName, FunctionId) {
66        self.start_alternatives
67            .iter()
68            .find_map(|(name, fid)| match name {
69                StartAlternativeName::VFS(wasm_name) => Some((wasm_name.clone(), *fid)),
70                _ => None,
71            })
72            .expect("VFS start alternative must exist")
73    }
74
75    pub fn iter(&self) -> impl Iterator<Item = (&StartAlternativeName, FunctionId)> {
76        self.start_alternatives.iter().map(|(a, b)| (a, *b))
77    }
78
79    pub fn target_wasm_fids(&self) -> impl Iterator<Item = (&WasmName, FunctionId)> {
80        self.start_alternatives
81            .iter()
82            .filter_map(move |(name, fid)| match name {
83                StartAlternativeName::WasmName(wasm_name) => Some((wasm_name, *fid)),
84                _ => None,
85            })
86    }
87
88    pub fn check_is_builded(&self) {
89        if self.is_builded {
90            panic!("StartSectionCommon has already been built");
91        }
92    }
93}
94
95#[derive(Debug, Default)]
96pub struct StartSectionGenerator {
97    common: Option<Arc<parking_lot::Mutex<StartSectionCommon>>>,
98}
99
100impl StartSectionGenerator {
101    pub fn init(
102        &mut self,
103        module: &mut walrus::Module,
104        vfs_name: WasmName,
105        wasm_names: &[WasmName],
106    ) {
107        if let Some(_) = &self.common {
108            // let mut common = common.lock();
109            // common.start_alternatives.clear();
110            // for name in wasm_names {
111            //     let unique_name = Self::unique_import_name(name);
112            //     // if (UniqueName::NAMESPACE, &unique_name).get_fid(&module.imports).is_ok() {
113            //     //     panic!("Import function for start alternative '{name}' already exists");
114            //     // }
115            //     let fid = (UniqueName::NAMESPACE, &unique_name)
116            //         .get_fid(&module.imports)
117            //         .unwrap_or_else(|_| {
118            //             let func_ty = module.types.add(&[], &[]);
119            //             let (new_fid, _) = module.add_import_func(UniqueName::NAMESPACE, &unique_name, func_ty);
120            //             new_fid
121            //         });
122            //     common.start_alternatives.insert(name.clone(), fid);
123            // }
124            panic!("Re-initialization of StartSectionGenerator is not supported");
125        } else {
126            let func_ty = module.types.add(&[], &[]);
127            let common = StartSectionCommon {
128                map: Vec::new(),
129                is_builded: false,
130                start_alternatives: core::iter::once(StartAlternativeName::VFS(vfs_name.clone()))
131                    .chain(core::iter::once(StartAlternativeName::AfterMemoryReset))
132                    .chain(
133                        wasm_names
134                            .iter()
135                            .cloned()
136                            .map(StartAlternativeName::WasmName),
137                    )
138                    .map(|name| {
139                        let unique_name = UniqueName::StartAlternative(&name);
140                        if (UniqueName::NAMESPACE, &unique_name)
141                            .get_fid(&module.imports)
142                            .is_ok()
143                        {
144                            panic!(
145                                "Import function for start alternative '{name:?}' already exists"
146                            );
147                        }
148                        let (new_fid, _) = module.add_import_func(
149                            UniqueName::NAMESPACE,
150                            &unique_name.to_string(),
151                            func_ty,
152                        );
153                        (name, new_fid)
154                    })
155                    .collect(),
156            };
157            self.common = Some(Arc::new(parking_lot::Mutex::new(common)));
158        }
159    }
160
161    pub fn builder(&self) -> StartSectionBuilder {
162        match &self.common {
163            None => panic!("StartSectionGenerator is not initialized"),
164            Some(common) => {
165                if common.lock().is_builded {
166                    panic!("StartSectionGenerator has already been built");
167                }
168            }
169        }
170
171        StartSectionBuilder {
172            common: self.common.as_ref().unwrap().clone(),
173        }
174    }
175
176    pub fn build(self, module: &mut walrus::Module, ctx: &GeneratorCtx) -> eyre::Result<()> {
177        let common = self.common.unwrap();
178        let mut common = common.lock();
179        common.is_builded = true;
180
181        // todo!();
182
183        for info in common
184            .map
185            .iter_mut()
186            .filter(|info| matches!(info.priority, StartFnPriority::AfterAll))
187        {
188            match &mut info.source {
189                StartSource::ExportFunc(name) => {
190                    unimplemented!();
191                }
192                StartSource::Rewrite(f) => {
193                    if let Some(f) = f.take() {
194                        f(module, ctx)?;
195                    } else {
196                        panic!("StartSource::Rewrite function has already been taken");
197                    }
198                }
199            }
200        }
201
202        Ok(())
203    }
204}
205
206impl Generator for StartSectionGenerator {}
207
208#[derive(Debug, Clone)]
209pub struct StartSectionBuilder {
210    common: Arc<parking_lot::Mutex<StartSectionCommon>>,
211}
212
213impl StartSectionBuilder {
214    pub fn iter(&self) -> Vec<(StartAlternativeName, FunctionId)> {
215        self.common
216            .lock()
217            .start_alternatives
218            .iter()
219            .map(|(name, fid)| (name.clone(), *fid))
220            .collect::<Vec<_>>()
221    }
222
223    pub fn vfs_start_fid(&self) -> (WasmName, FunctionId) {
224        self.common.lock().vfs_start_fid()
225    }
226
227    pub fn after_memory_reset_fid(&self) -> FunctionId {
228        self.common
229            .lock()
230            .start_alternatives
231            .get(&StartAlternativeName::AfterMemoryReset)
232            .copied()
233            .expect("AfterMemoryReset start alternative must exist")
234    }
235
236    pub fn target_wasm_fids(&self) -> Vec<(WasmName, FunctionId)> {
237        self.common
238            .lock()
239            .target_wasm_fids()
240            .map(|(name, fid)| (name.clone(), fid))
241            .collect::<Vec<_>>()
242    }
243
244    pub fn add_start_fn(&self, info: StartFnInfo) {
245        self.common.lock().check_is_builded();
246
247        self.common.lock().map.push(info);
248    }
249}