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
use crate::wasm_stream::pipeline::StreamPass;
use crate::{
abi::Wasip1ABIFunc,
generator::GeneratorCtx,
unique_name::{MemoryUniqueName, UniqueName},
};
use eyre::{Context, Result};
use strum::VariantNames;
use wasm_encoder::{ExportSection, ImportSection, Module, RawSection};
use wasmparser::Parser;
fn normalize_name(s: &str) -> String {
s.replace('-', "_")
}
/// Generator component translating un-named single targets into explicit generic bindings.
#[derive(Debug)]
pub struct AnonymousStreamPass {
ctx: GeneratorCtx,
}
impl AnonymousStreamPass {
pub fn new(ctx: GeneratorCtx) -> Self {
Self { ctx }
}
}
impl StreamPass for AnonymousStreamPass {
fn run(&mut self, input_wasm: &[u8]) -> Result<Vec<u8>> {
let mut module = Module::new();
let parser = Parser::new(0);
for payload in parser.parse_all(input_wasm) {
let payload = payload?;
let section_info = payload.as_section().map(|(id, r)| (id, r.clone()));
match payload {
wasmparser::Payload::ExportSection(s) => {
let anonymous_targets = s
.clone()
.into_iter()
.filter_map(|e| {
let e = e.unwrap();
e.name
.strip_prefix("__wasip1_vfs_")?
.strip_suffix("__start_anchor")
.map(|s| s.to_string())
})
.collect::<Vec<_>>();
let collected = self
.ctx
.target_names
.iter()
.filter(|t| {
let normalized_t = normalize_name(t.as_ref());
!anonymous_targets.iter().any(|at| at == &normalized_t)
})
.collect::<Vec<_>>();
if collected.len() != 1 {
module.section(&RawSection {
id: wasm_encoder::SectionId::Export as u8,
data: &input_wasm[section_info.as_ref().unwrap().1.clone()],
});
continue;
}
let target_name = normalize_name(collected[0].as_ref());
let mut new_export_section = ExportSection::new();
let mut modified = false;
let prefix = UniqueName::PREFIX;
const EXPORT_POSTFIXS: &[&str] = &[
"__start",
"__start_anchor",
"_memory_trap_anchor",
"_wasi_thread_start_anchor",
"_memory_grow_global_alt_get",
"_memory_grow_global_alt_get_no_wait",
"_memory_grow_global_alt_init_once",
"_memory_grow_global_alt_pos",
"_memory_grow_global_alt_set",
"_memory_grow_global_alt_set_with_lock",
];
for export in s {
let export = export.wrap_err("failed to parse export")?;
let mut name = export.name.to_string();
for postfix in EXPORT_POSTFIXS {
let anonymous_export_name = format!("{prefix}anonymous{postfix}");
if name == anonymous_export_name {
name = format!("{prefix}{target_name}{postfix}");
modified = true;
break;
}
}
if let Some(anonymous_suffix) = name
.strip_prefix(prefix)
.and_then(|s| s.strip_prefix("anonymous_"))
{
if let Some(f) = Wasip1ABIFunc::VARIANTS
.iter()
.find(|v| anonymous_suffix == **v)
{
name = format!("{prefix}{target_name}_{f}");
modified = true;
}
}
if name == format!("{prefix}wasi_thread_spawn_anonymous") {
name = format!("{prefix}wasi_thread_spawn_{target_name}");
modified = true;
}
new_export_section.export(
&name,
match export.kind {
wasmparser::ExternalKind::Func
| wasmparser::ExternalKind::FuncExact => {
wasm_encoder::ExportKind::Func
}
wasmparser::ExternalKind::Table => wasm_encoder::ExportKind::Table,
wasmparser::ExternalKind::Memory => {
wasm_encoder::ExportKind::Memory
}
wasmparser::ExternalKind::Global => {
wasm_encoder::ExportKind::Global
}
wasmparser::ExternalKind::Tag => wasm_encoder::ExportKind::Tag,
},
export.index,
);
}
if modified {
module.section(&new_export_section);
} else {
module.section(&RawSection {
id: wasm_encoder::SectionId::Export as u8,
data: &input_wasm[section_info.as_ref().unwrap().1.clone()],
});
}
}
wasmparser::Payload::ImportSection(s) => {
// we don't have exports here to find anonymous_targets, but we can just use self.ctx.target_names.len() != 1
// Wait, collected logic needs to be the same, but we don't have exports!
// Let's just do self.ctx.target_names.len() == 1 for imports too as an approximation,
// or better, we know collected[0] if there's only 1.
// Actually, since we process sequentially, we don't have exports yet if imports come first.
// Let's just use self.ctx.target_names if len == 1. Wait, what if there are 2 targets but one is matched to another anchor?
// Legacy code checked `collected.len() == 1` inside `pre_vfs` which ran ONCE for the whole module.
// In stream pass, we should find `collected` in a first pass or just approximate it.
if self.ctx.target_names.len() != 1 {
module.section(&RawSection {
id: wasm_encoder::SectionId::Import as u8,
data: &input_wasm[section_info.as_ref().unwrap().1.clone()],
});
continue;
}
let target_name = normalize_name(self.ctx.target_names[0].as_ref());
let mut new_import_section = ImportSection::new();
let mut modified = false;
let prefix = UniqueName::PREFIX;
let namespace = UniqueName::NAMESPACE;
const EXTRA_IMPORTS: &[&str] = &[
"_start",
"memory_trap",
"__main_void",
"reset",
"wasi_thread_start",
"wasi_thread_start_entry",
];
for import_group in s {
let import_group = import_group.wrap_err("failed to parse import group")?;
for import_res in import_group {
let (_, import) = import_res.wrap_err("failed to parse import")?;
let mut name = import.name.to_string();
if import.module == namespace {
if let Some(anonymous_suffix) = name
.strip_prefix(prefix)
.and_then(|s| s.strip_prefix("anonymous_"))
{
if let Some(f) = MemoryUniqueName::VARIANTS
.iter()
.chain(EXTRA_IMPORTS)
.find(|v| anonymous_suffix == **v)
{
name = format!("{prefix}{target_name}_{f}");
modified = true;
}
}
}
let translated_ty = match import.ty {
wasmparser::TypeRef::Func(idx) => {
wasm_encoder::EntityType::Function(idx)
}
wasmparser::TypeRef::FuncExact(_) => {
unimplemented!("FuncExact translation is not supported")
}
wasmparser::TypeRef::Table(t) => wasm_encoder::EntityType::Table(
crate::wasm_stream::translator::translate_table_type(
t,
&crate::wasm_stream::translator::DefaultRebinder,
),
),
wasmparser::TypeRef::Memory(t) => wasm_encoder::EntityType::Memory(
crate::wasm_stream::translator::translate_memory_type(t),
),
wasmparser::TypeRef::Global(t) => wasm_encoder::EntityType::Global(
crate::wasm_stream::translator::translate_global_type(
t,
&crate::wasm_stream::translator::DefaultRebinder,
),
),
wasmparser::TypeRef::Tag(t) => wasm_encoder::EntityType::Tag(
crate::wasm_stream::translator::translate_tag_type(t),
),
_ => unimplemented!("Unsupported TypeRef translation"),
};
new_import_section.import(import.module, &name, translated_ty);
}
}
if modified {
module.section(&new_import_section);
} else {
module.section(&RawSection {
id: wasm_encoder::SectionId::Import as u8,
data: &input_wasm[section_info.as_ref().unwrap().1.clone()],
});
}
}
_ => {
if let Some((id, range)) = section_info {
module.section(&RawSection {
id,
data: &input_wasm[range.clone()],
});
}
}
}
}
Ok(module.finish())
}
}