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