-
Notifications
You must be signed in to change notification settings - Fork 27
/
lib.rs
410 lines (376 loc) · 12.2 KB
/
lib.rs
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
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
use anyhow::{bail, Context, Result};
use bindgen::BindingItem;
use std::{
path::{Path, PathBuf},
vec,
};
mod bindgen;
mod splice;
mod stub_wasi;
use crate::stub_wasi::stub_wasi;
use wasm_encoder::{Encode, Section};
use wit_component::{
metadata::{decode, Bindgen},
StringEncoding,
};
use wit_parser::{PackageId, Resolve};
wit_bindgen::generate!({
world: "spidermonkey-embedding-splicer",
});
struct SpidermonkeyEmbeddingSplicerComponent;
/// Calls [`write!`] with the passed arguments and unwraps the result.
///
/// Useful for writing to things with infallible `Write` implementations like
/// `Source` and `String`.
///
/// [`write!`]: std::write
#[macro_export]
macro_rules! uwrite {
($dst:expr, $($arg:tt)*) => {
write!($dst, $($arg)*).unwrap()
};
}
/// Calls [`writeln!`] with the passed arguments and unwraps the result.
///
/// Useful for writing to things with infallible `Write` implementations like
/// `Source` and `String`.
///
/// [`writeln!`]: std::writeln
#[macro_export]
macro_rules! uwriteln {
($dst:expr, $($arg:tt)*) => {
writeln!($dst, $($arg)*).unwrap()
};
}
fn map_core_ty(cty: &bindgen::CoreTy) -> CoreTy {
match cty {
bindgen::CoreTy::I32 => CoreTy::I32,
bindgen::CoreTy::I64 => CoreTy::I64,
bindgen::CoreTy::F32 => CoreTy::F32,
bindgen::CoreTy::F64 => CoreTy::F64,
}
}
fn map_core_fn(cfn: &bindgen::CoreFn) -> CoreFn {
let bindgen::CoreFn {
params,
ret,
retptr,
retsize,
paramptr,
} = cfn;
CoreFn {
params: params.iter().map(&map_core_ty).collect(),
ret: match ret {
Some(ref core_ty) => Some(map_core_ty(core_ty)),
None => None,
},
retptr: *retptr,
retsize: *retsize,
paramptr: *paramptr,
}
}
fn parse_wit(path: &Path) -> Result<(Resolve, PackageId)> {
let mut resolve = Resolve::default();
let id = if path.is_dir() {
resolve.push_dir(&path)?.0
} else {
let contents =
std::fs::read(&path).with_context(|| format!("failed to read file {path:?}"))?;
let text = match std::str::from_utf8(&contents) {
Ok(s) => s,
Err(_) => bail!("input file is not valid utf-8"),
};
resolve.push_str(&path, text)?
};
Ok((resolve, id))
}
impl Guest for SpidermonkeyEmbeddingSplicerComponent {
fn stub_wasi(
wasm: Vec<u8>,
features: Vec<Features>,
wit_source: Option<String>,
wit_path: Option<String>,
world_name: Option<String>,
) -> Result<Vec<u8>, String> {
stub_wasi(wasm, features, wit_source, wit_path, world_name).map_err(|e| e.to_string())
}
fn splice_bindings(
source_name: Option<String>,
engine: Vec<u8>,
wit_source: Option<String>,
wit_path: Option<String>,
world_name: Option<String>,
mut guest_imports: Vec<String>,
guest_exports: Vec<String>,
features: Vec<Features>,
debug: bool,
) -> Result<SpliceResult, String> {
let source_name = source_name.unwrap_or("source.js".to_string());
let (mut resolve, id) = if let Some(wit_source) = wit_source {
let mut resolve = Resolve::default();
let path = PathBuf::from("component.wit");
let id = resolve
.push_str(&path, &wit_source)
.map_err(|e| e.to_string())?;
(resolve, id)
} else {
parse_wit(&PathBuf::from(wit_path.unwrap())).map_err(|e| format!("{:?}", e))?
};
let world = resolve
.select_world(id, world_name.as_deref())
.map_err(|e| e.to_string())?;
let mut wasm_bytes = wit_component::dummy_module(&resolve, world);
// merge the engine world with the target world, retaining the engine producers
let producers = if let Ok((
_,
Bindgen {
resolve: mut engine_resolve,
world: engine_world,
metadata: _,
producers,
},
)) = decode(&engine)
{
// merge the imports from the engine with the imports from the guest content
for (k, _) in &engine_resolve.worlds[engine_world].imports {
guest_imports.push(engine_resolve.name_world_key(k));
}
// we disable the engine run and incoming handler as we recreate these exports
// when needed, so remove these from the world before initiating the merge
let maybe_run = engine_resolve.worlds[engine_world]
.exports
.iter()
.find(|(key, _)| engine_resolve.name_world_key(key) == "wasi:cli/[email protected]")
.map(|(key, _)| key.clone());
if let Some(run) = maybe_run {
engine_resolve.worlds[engine_world]
.exports
.shift_remove(&run)
.unwrap();
}
let maybe_serve = engine_resolve.worlds[engine_world]
.exports
.iter()
.find(|(key, _)| {
engine_resolve.name_world_key(key) == "wasi:http/[email protected]"
})
.map(|(key, _)| key.clone());
if let Some(serve) = maybe_serve {
engine_resolve.worlds[engine_world]
.exports
.shift_remove(&serve)
.unwrap();
}
resolve
.merge(engine_resolve)
.expect("unable to merge with engine world");
producers
} else {
None
};
let componentized = bindgen::componentize_bindgen(
&resolve,
world,
&source_name,
&guest_imports,
&guest_exports,
features,
)
.map_err(|err| err.to_string())?;
let (engine_world, _) = resolve
.worlds
.iter()
.find(|(world, _)| resolve.worlds[*world].name == "root")
.unwrap();
resolve
.merge_worlds(engine_world, world)
.expect("unable to merge with engine world");
let encoded = wit_component::metadata::encode(
&resolve,
world,
StringEncoding::UTF8,
producers.as_ref(),
)
.map_err(|e| e.to_string())?;
let section = wasm_encoder::CustomSection {
name: "component-type".into(),
data: encoded.into(),
};
wasm_bytes.push(section.id());
section.encode(&mut wasm_bytes);
let mut generated_bindings = componentized.js_bindings;
// let mut imports_mapped = Vec::new();
// for impt in componentized.imports {
// }
// these should be temporary bindings fixups
if generated_bindings.contains("utf8Encode") {
generated_bindings = generated_bindings.replace(
"function utf8Encode(s, realloc, memory) {
if (typeof s !== 'string') throw new TypeError('expected a string');
if (s.length === 0) {
utf8EncodedLen = 0;
return 1;
}
let allocLen = 0;
let ptr = 0;
let writtenTotal = 0;
while (s.length > 0) {
ptr = realloc(ptr, allocLen, 1, allocLen + s.length);
allocLen += s.length;
const { read, written } = utf8Encoder.encodeInto(
s,
new Uint8Array(memory.buffer, ptr + writtenTotal, allocLen - writtenTotal),
);
writtenTotal += written;
s = s.slice(read);
}
if (allocLen > writtenTotal)
ptr = realloc(ptr, allocLen, 1, writtenTotal);
utf8EncodedLen = writtenTotal;
return ptr;
}",
"function utf8Encode(s, realloc, memory) {
const buf = utf8Encoder.encode(s);
const ptr = realloc(0, 0, 1, buf.byteLength);
const out = new Uint8Array(memory.buffer, ptr, buf.byteLength);
for (let i = 0; i < buf.byteLength; i++) {
out[i] = buf[i];
}
utf8EncodedLen = buf.byteLength;
return ptr;
}",
);
}
let mut exports = Vec::new();
for (
export_name,
BindingItem {
name,
func,
iface,
resource,
..
},
) in &componentized.exports
{
let expt = if *iface {
let name = resource.canon_string(&name);
format!("{export_name}#{name}")
} else {
export_name.clone()
};
exports.push((expt, map_core_fn(func)));
}
let mut imports = Vec::new();
for (
specifier,
BindingItem {
name,
func,
iface,
resource,
..
},
) in &componentized.imports
{
if *iface {
imports.push((
specifier.to_string(),
resource.canon_string(&name),
map_core_fn(func),
if func.retsize > 0 {
Some(func.retsize as i32)
} else {
None
},
));
} else {
imports.push((
"$root".into(),
specifier.to_string(),
map_core_fn(func),
if func.retsize > 0 {
Some(func.retsize as i32)
} else {
None
},
));
}
}
for (key, name, return_count) in &componentized.resource_imports {
imports.push((
key.clone(),
name.clone(),
CoreFn {
params: vec![CoreTy::I32],
ret: if *return_count == 0 {
None
} else {
Some(CoreTy::I32)
},
retptr: false,
retsize: 0,
paramptr: false,
},
Some(i32::try_from(*return_count).unwrap()),
));
}
// println!("{:?}", &componentized.imports);
// println!("{:?}", &componentized.resource_imports);
// println!("{:?}", &exports);
let mut wasm =
splice::splice(engine, imports, exports, debug).map_err(|e| format!("{:?}", e))?;
// add the world section to the spliced wasm
wasm.push(section.id());
section.encode(&mut wasm);
Ok(SpliceResult {
wasm,
exports: componentized
.exports
.iter()
.map(
|(
_,
BindingItem {
binding_name, func, ..
},
)| { (binding_name.to_string(), map_core_fn(&func)) },
)
.collect(),
imports: componentized
.imports
.iter()
.map(
|(
specifier,
BindingItem {
name,
iface,
func,
resource,
..
},
)| {
(
if *iface {
specifier.to_string()
} else {
"$root".into()
},
if *iface {
resource.canon_string(&name)
} else {
specifier.to_string()
},
func.params.len() as u32,
)
},
)
.chain(componentized.resource_imports)
.collect(),
import_wrappers: componentized.import_wrappers,
js_bindings: generated_bindings,
})
}
}
export!(SpidermonkeyEmbeddingSplicerComponent);