wasi_virt_layer_cli/generator/
start_section.rs1use 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#[derive(Debug, Clone)]
14pub enum StartFnPriority {
15 AfterMemoryReset,
17 AfterAll,
19}
20
21#[derive(Debug)]
23pub struct StartFnInfo {
24 pub priority: StartFnPriority,
26 pub source: StartSource,
28}
29
30pub enum StartSource {
32 ExportFunc(String),
34 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")]
53pub enum StartAlternativeName {
55 WasmName(WasmName),
57 VFS(WasmName),
59 AfterMemoryReset,
62}
63
64#[derive(Debug, Default)]
66pub struct StartSectionCommon {
67 map: Vec<StartFnInfo>,
69 start_alternatives: HashMap<StartAlternativeName, FunctionId>,
71 is_builded: bool,
72}
73
74impl StartSectionCommon {
75 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 pub fn iter(&self) -> impl Iterator<Item = (&StartAlternativeName, FunctionId)> {
88 self.start_alternatives.iter().map(|(a, b)| (a, *b))
89 }
90
91 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 pub fn check_is_builded(&self) {
103 if self.is_builded {
104 panic!("StartSectionCommon has already been built");
105 }
106 }
107}
108
109#[derive(Debug, Default)]
111pub struct StartSectionGenerator {
112 common: Option<Arc<parking_lot::Mutex<StartSectionCommon>>>,
113}
114
115impl StartSectionGenerator {
116 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 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 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 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 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#[derive(Debug, Clone)]
228pub struct StartSectionBuilder {
229 common: Arc<parking_lot::Mutex<StartSectionCommon>>,
230}
231
232impl StartSectionBuilder {
233 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 pub fn vfs_start_fid(&self) -> (WasmName, FunctionId) {
245 self.common.lock().vfs_start_fid()
246 }
247
248 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 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 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}