Add wasm2elf: i32 WebAssembly to static x86-64 ELF compiler in MoonBit
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
commit
b8617c7aaa
22 files changed
+1219
No files matched your search
+228
@@ -0,0 +1,228 @@
|
||||
///|
|
||||
fn expect_i32(r : Reader) -> Unit raise CompileError {
|
||||
let t = r.byte()
|
||||
if t != 0x7F {
|
||||
raise CompileError("only i32 value types are supported (got 0x\{t.to_string(radix=16)})")
|
||||
}
|
||||
}
|
||||
|
||||
///|
|
||||
fn le(out : Array[Byte], v : Int, n : Int) -> Unit {
|
||||
for i in 0..<n {
|
||||
out.push(((v >> (8 * i)) & 0xFF).to_byte())
|
||||
}
|
||||
}
|
||||
|
||||
///|
|
||||
const BASE : Int = 0x400000
|
||||
|
||||
///|
|
||||
const HEADERS : Int = 120
|
||||
|
||||
///|
|
||||
let messages : Array[String] = [
|
||||
"wasm trap: unreachable\n", "wasm trap: integer divide by zero\n", "wasm trap: integer overflow\n",
|
||||
]
|
||||
|
||||
///|
|
||||
/// Compile a WebAssembly binary (i32-only subset, no imports/memory/globals)
|
||||
/// to a static x86-64 Linux ELF executable. The entry export is called from
|
||||
/// `_start` and its i32 result becomes the process exit code.
|
||||
pub fn compile(wasm : Bytes, entry : String?) -> Bytes raise CompileError {
|
||||
if wasm.length() < 8 ||
|
||||
wasm[0] != b'\x00' ||
|
||||
wasm[1] != b'a' ||
|
||||
wasm[2] != b's' ||
|
||||
wasm[3] != b'm' {
|
||||
raise CompileError("not a WebAssembly binary")
|
||||
}
|
||||
let r = Reader::new(wasm, 8)
|
||||
let types : Array[FuncType] = []
|
||||
let func_types : Array[Int] = []
|
||||
let exports : Array[(String, Int)] = []
|
||||
let bodies : Array[(Int, Int)] = [] // (start of locals, end)
|
||||
while r.pos < wasm.length() {
|
||||
let id = r.byte()
|
||||
let size = r.u32()
|
||||
let end = r.pos + size
|
||||
match id {
|
||||
0 => ()
|
||||
1 =>
|
||||
for _ in 0..<r.u32() {
|
||||
if r.byte() != 0x60 {
|
||||
raise CompileError("bad function type")
|
||||
}
|
||||
let np = r.u32()
|
||||
for _ in 0..<np {
|
||||
expect_i32(r)
|
||||
}
|
||||
let nr = r.u32()
|
||||
if nr > 1 {
|
||||
raise CompileError("multi-value results are not supported")
|
||||
}
|
||||
for _ in 0..<nr {
|
||||
expect_i32(r)
|
||||
}
|
||||
types.push({ nparams: np, nresults: nr })
|
||||
}
|
||||
3 =>
|
||||
for _ in 0..<r.u32() {
|
||||
func_types.push(r.u32())
|
||||
}
|
||||
7 =>
|
||||
for _ in 0..<r.u32() {
|
||||
let name = r.name()
|
||||
let kind = r.byte()
|
||||
let idx = r.u32()
|
||||
if kind == 0 {
|
||||
exports.push((name, idx))
|
||||
}
|
||||
}
|
||||
10 =>
|
||||
for _ in 0..<r.u32() {
|
||||
let sz = r.u32()
|
||||
bodies.push((r.pos, r.pos + sz))
|
||||
r.pos += sz
|
||||
}
|
||||
_ =>
|
||||
raise CompileError(
|
||||
"unsupported section id \{id} (imports, tables, memory, globals, start, data are not supported)",
|
||||
)
|
||||
}
|
||||
r.pos = end
|
||||
}
|
||||
if bodies.length() != func_types.length() {
|
||||
raise CompileError("function/code section length mismatch")
|
||||
}
|
||||
// choose entry
|
||||
let entry_idx = match entry {
|
||||
Some(n) =>
|
||||
match exports.search_by(fn(e) { e.0 == n }) {
|
||||
Some(i) => exports[i].1
|
||||
None => raise CompileError("no exported function named \{n}")
|
||||
}
|
||||
None => {
|
||||
let pick = fn(n : String) { exports.search_by(fn(e) { e.0 == n }) }
|
||||
match pick("_start") {
|
||||
Some(i) => exports[i].1
|
||||
None =>
|
||||
match pick("main") {
|
||||
Some(i) => exports[i].1
|
||||
None =>
|
||||
if exports.length() > 0 {
|
||||
exports[0].1
|
||||
} else {
|
||||
raise CompileError("module exports no functions")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if entry_idx >= func_types.length() || types[func_types[entry_idx]].nparams != 0 {
|
||||
raise CompileError("entry function must exist and take no parameters")
|
||||
}
|
||||
// compile all functions
|
||||
let fns : Array[Fn] = []
|
||||
for i in 0..<bodies.length() {
|
||||
let (start, end) = bodies[i]
|
||||
let br = Reader::new(wasm, start)
|
||||
let mut nlocals = types[func_types[i]].nparams
|
||||
for _ in 0..<br.u32() {
|
||||
let count = br.u32()
|
||||
expect_i32(br)
|
||||
nlocals += count
|
||||
}
|
||||
fns.push(
|
||||
compile_body(br, end, types[func_types[i]], nlocals, types, func_types),
|
||||
)
|
||||
}
|
||||
// layout: _start | trap stubs | functions | messages
|
||||
let a = Asm::new()
|
||||
let start_call = a.rel([0xE8])
|
||||
a.bs([0x89, 0xC7]) // mov edi,eax
|
||||
if types[func_types[entry_idx]].nresults == 0 {
|
||||
a.bs([0x31, 0xFF]) // xor edi,edi
|
||||
}
|
||||
a.bs([0xB8, 0xE7, 0x00, 0x00, 0x00, 0x0F, 0x05]) // exit_group
|
||||
let stub_at : Array[Int] = []
|
||||
let lea_at : Array[Int] = []
|
||||
for _ in 0..<3 {
|
||||
stub_at.push(a.here())
|
||||
lea_at.push(a.rel([0x48, 0x8D, 0x35])) // lea rsi,[rip+msg]
|
||||
a.b(0xBA) // mov edx,len (filled below)
|
||||
a.i32(0)
|
||||
a.bs([0xBF, 0x02, 0x00, 0x00, 0x00]) // mov edi,2
|
||||
a.bs([0xB8, 0x01, 0x00, 0x00, 0x00, 0x0F, 0x05]) // write
|
||||
a.bs([0xBF, 0x86, 0x00, 0x00, 0x00]) // mov edi,134
|
||||
a.bs([0xB8, 0xE7, 0x00, 0x00, 0x00, 0x0F, 0x05]) // exit_group
|
||||
}
|
||||
let fn_at : Array[Int] = []
|
||||
for f in fns {
|
||||
let off = a.here()
|
||||
fn_at.push(off)
|
||||
for c in f.code.code {
|
||||
a.code.push(c)
|
||||
}
|
||||
for (at, kind) in f.traps {
|
||||
a.patch(off + at, stub_at[kind])
|
||||
}
|
||||
}
|
||||
// patch calls now that every function's address is known
|
||||
for i in 0..<fns.length() {
|
||||
for (at, callee) in fns[i].calls {
|
||||
a.patch(fn_at[i] + at, fn_at[callee])
|
||||
}
|
||||
}
|
||||
a.patch(start_call, fn_at[entry_idx])
|
||||
for k in 0..<3 {
|
||||
let msg = messages[k]
|
||||
a.patch(lea_at[k], a.here())
|
||||
// fill `mov edx,len` imm32 right after the lea rel32
|
||||
let imm = lea_at[k] + 4 + 1
|
||||
let n = msg.length()
|
||||
a.code[imm] = (n & 0xFF).to_byte()
|
||||
for ch in msg {
|
||||
a.code.push(ch.to_int().to_byte())
|
||||
}
|
||||
}
|
||||
// ELF header + one PT_LOAD program header
|
||||
let out : Array[Byte] = []
|
||||
for b in [0x7F, 0x45, 0x4C, 0x46, 2, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0] {
|
||||
out.push(b.to_byte())
|
||||
}
|
||||
le(out, 2, 2) // ET_EXEC
|
||||
le(out, 0x3E, 2) // x86-64
|
||||
le(out, 1, 4)
|
||||
le(out, BASE + HEADERS, 4)
|
||||
le(out, 0, 4) // entry (high)
|
||||
le(out, 64, 4) // phoff
|
||||
le(out, 0, 4)
|
||||
le(out, 0, 8) // shoff
|
||||
le(out, 0, 4) // flags
|
||||
le(out, 64, 2)
|
||||
le(out, 56, 2)
|
||||
le(out, 1, 2)
|
||||
le(out, 0, 2)
|
||||
le(out, 0, 2)
|
||||
le(out, 0, 2)
|
||||
let total = HEADERS + a.here()
|
||||
le(out, 1, 4) // PT_LOAD
|
||||
le(out, 5, 4) // R+X
|
||||
le(out, 0, 8) // offset
|
||||
le(out, BASE, 4)
|
||||
le(out, 0, 4)
|
||||
le(out, BASE, 4)
|
||||
le(out, 0, 4)
|
||||
le(out, total, 4)
|
||||
le(out, 0, 4)
|
||||
le(out, total, 4)
|
||||
le(out, 0, 4)
|
||||
le(out, 0x1000, 8)
|
||||
while out.length() < HEADERS {
|
||||
out.push(b'\x00')
|
||||
}
|
||||
for c in a.code {
|
||||
out.push(c)
|
||||
}
|
||||
Bytes::from_array(out)
|
||||
}
|
||||
Reference in new issue
Block a user