2021-11-13 02:52:35 -06:00
|
|
|
//! Frontend: convert Wasm to IR.
|
|
|
|
|
|
|
|
use crate::ir::*;
|
2021-11-13 03:10:22 -06:00
|
|
|
use anyhow::anyhow;
|
2021-11-13 02:56:49 -06:00
|
|
|
use anyhow::Result;
|
|
|
|
use log::trace;
|
2021-11-13 03:10:22 -06:00
|
|
|
use std::collections::VecDeque;
|
2021-11-13 02:59:15 -06:00
|
|
|
use wasmparser::{ImportSectionEntryType, Parser, Payload, TypeDef};
|
2021-11-13 02:52:35 -06:00
|
|
|
|
|
|
|
pub fn wasm_to_ir(bytes: &[u8]) -> Result<Module> {
|
|
|
|
let mut module = Module::default();
|
2021-11-13 02:56:49 -06:00
|
|
|
let parser = Parser::new(0);
|
2021-11-13 03:10:22 -06:00
|
|
|
let mut sigs = VecDeque::new();
|
2021-11-13 02:56:49 -06:00
|
|
|
for payload in parser.parse_all(bytes) {
|
|
|
|
let payload = payload?;
|
2021-11-13 03:10:22 -06:00
|
|
|
handle_payload(&mut module, payload, &mut sigs)?;
|
2021-11-13 02:52:35 -06:00
|
|
|
}
|
|
|
|
|
|
|
|
Ok(module)
|
|
|
|
}
|
|
|
|
|
2021-11-13 03:10:22 -06:00
|
|
|
fn handle_payload<'a>(
|
|
|
|
module: &mut Module,
|
|
|
|
payload: Payload<'a>,
|
|
|
|
func_sigs: &mut VecDeque<SignatureId>,
|
|
|
|
) -> Result<()> {
|
2021-11-13 02:56:49 -06:00
|
|
|
trace!("Wasm parser item: {:?}", payload);
|
2021-11-13 02:52:35 -06:00
|
|
|
match payload {
|
|
|
|
Payload::TypeSection(mut reader) => {
|
|
|
|
for _ in 0..reader.get_count() {
|
|
|
|
let ty = reader.read()?;
|
|
|
|
match ty {
|
|
|
|
TypeDef::Func(fty) => {
|
|
|
|
module.signatures.push(fty);
|
|
|
|
}
|
|
|
|
_ => {}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2021-11-13 02:59:15 -06:00
|
|
|
Payload::ImportSection(mut reader) => {
|
|
|
|
for _ in 0..reader.get_count() {
|
|
|
|
match reader.read()?.ty {
|
|
|
|
ImportSectionEntryType::Function(sig_idx) => {
|
|
|
|
module.funcs.push(FuncDecl::Import(sig_idx as SignatureId));
|
|
|
|
}
|
|
|
|
_ => {}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2021-11-13 03:10:22 -06:00
|
|
|
Payload::FunctionSection(mut reader) => {
|
|
|
|
for _ in 0..reader.get_count() {
|
|
|
|
func_sigs.push_back(reader.read()? as SignatureId);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
Payload::CodeSectionEntry(body) => {
|
|
|
|
let sig = func_sigs
|
|
|
|
.pop_front()
|
|
|
|
.ok_or_else(|| anyhow!("mismatched func section and code section sizes"))?;
|
|
|
|
let body = parse_body(body)?;
|
|
|
|
module.funcs.push(FuncDecl::Body(sig as SignatureId, body));
|
|
|
|
}
|
2021-11-13 02:52:35 -06:00
|
|
|
_ => {}
|
|
|
|
}
|
|
|
|
|
|
|
|
Ok(())
|
|
|
|
}
|
2021-11-13 03:10:22 -06:00
|
|
|
|
|
|
|
fn parse_body(body: wasmparser::FunctionBody) -> Result<FunctionBody> {
|
|
|
|
let mut ret = FunctionBody::default();
|
|
|
|
let mut locals = body.get_locals_reader()?;
|
|
|
|
for _ in 0..locals.get_count() {
|
|
|
|
let (count, ty) = locals.read()?;
|
|
|
|
for _ in 0..count {
|
|
|
|
ret.locals.push(ty);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
Ok(ret)
|
|
|
|
}
|