Files
nandiandClaude Sonnet 5.5 fdc1cd4b3c Add bulk memory ops and raw syscall intrinsics
- memory.copy / memory.fill (0xFC 0x0A/0x0B) with bounds checks via rep movsb/stosb
- module "sys" host intrinsics for hand-written wasm shims: syscall, membase,
  argv_base, peek64, strlen, copy_in; _start saves the initial rsp for argv
  (only when the module has a data segment)

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-21 18:12:12 -08:00

515 lines
15 KiB
MoonBit

///|
fn expect_num(r : Reader) -> Unit raise CompileError {
let t = r.byte()
if t < 0x7C || t > 0x7F {
raise CompileError(
"only numeric value types are supported (got 0x\{t.to_string(radix=16)})",
)
}
}
///|
fn le(out : Array[Byte], v : Int32, n : Int32) -> Unit {
// little-endian, zero-extended past 32 bits (Int shifts wrap mod 32)
for i in 0..<n {
out.push(if i < 4 { ((v >> (8 * i)) & 0xFF).to_byte() } else { b'\x00' })
}
}
///|
const BASE : Int32 = 0x400000
///|
/// Read/write data segment: one page of globals, then linear memory.
const SEG_BASE : Int32 = 0x10000000
///|
const GLOB_BASE : Int32 = 0x10000000
///|
const MEM_BASE : Int32 = 0x10001000
///|
let messages : Array[String] = [
"wasm trap: unreachable\n", "wasm trap: integer divide by zero\n", "wasm trap: integer overflow\n",
"wasm trap: out of bounds memory access\n", "wasm trap: invalid conversion to integer\n",
]
///|
fn strip_version(m : String) -> String {
let sb = StringBuilder()
for ch in m {
if ch == '@' {
break
}
sb.write_char(ch)
}
sb.to_string()
}
///|
/// Native implementations of the lowered `wasi:cli` / `wasi:io` imports a
/// component's core module expects. Same calling convention as compiled
/// functions: args pushed left to right, caller cleans up, result in rax.
fn import_stub(m : String, name : String) -> Asm? {
let s = Asm::new()
s.bs([0x55, 0x48, 0x89, 0xE5]) // push rbp ; mov rbp,rsp
let key = strip_version(m) + "::" + name
match key {
"wasi:cli/stdin::get-stdin" => s.bs([0xB8, 0, 0, 0, 0])
"wasi:cli/stdout::get-stdout" => s.bs([0xB8, 1, 0, 0, 0])
"wasi:cli/stderr::get-stderr" => s.bs([0xB8, 2, 0, 0, 0])
"wasi:io/streams::[method]output-stream.blocking-write-and-flush" => {
// (self, ptr, len, retptr) -> () ; writes to fd `self`, stores `ok` at retptr
s.bs([0x8B, 0x7D, 0x28]) // mov edi,[rbp+40] self
s.bs([0x8B, 0x75, 0x20]) // mov esi,[rbp+32] ptr
s.bs([0x8B, 0x55, 0x18]) // mov edx,[rbp+24] len
s.bs([0x44, 0x8B, 0x45, 0x10]) // mov r8d,[rbp+16] retptr
s.bs([0x48, 0x81, 0xC6]) // add rsi, MEM_BASE
s.i32(MEM_BASE)
s.bs([0xB8, 0x01, 0x00, 0x00, 0x00, 0x0F, 0x05]) // write(fd, buf, len)
s.bs([0x41, 0xC6, 0x80]) // mov byte [r8+MEM_BASE], 0 (result::ok)
s.i32(MEM_BASE)
s.b(0)
}
// --- raw host intrinsics for hand-written wasm shims (module "sys") ---
"sys::syscall" => {
// (nr, a1..a6 : i64) -> i64
s.bs([0x48, 0x8B, 0x45, 0x40]) // mov rax,[rbp+64]
s.bs([0x48, 0x8B, 0x7D, 0x38]) // mov rdi,[rbp+56]
s.bs([0x48, 0x8B, 0x75, 0x30]) // mov rsi,[rbp+48]
s.bs([0x48, 0x8B, 0x55, 0x28]) // mov rdx,[rbp+40]
s.bs([0x4C, 0x8B, 0x55, 0x20]) // mov r10,[rbp+32]
s.bs([0x4C, 0x8B, 0x45, 0x18]) // mov r8,[rbp+24]
s.bs([0x4C, 0x8B, 0x4D, 0x10]) // mov r9,[rbp+16]
s.bs([0x0F, 0x05])
}
"sys::membase" => {
s.b(0xB8)
s.i32(MEM_BASE)
}
"sys::argv_base" => {
// initial rsp saved by _start (points at argc)
s.bs([0x48, 0x8B, 0x04, 0x25])
s.i32(GLOB_BASE + 0xFF8)
}
"sys::peek64" =>
// (host addr : i64) -> i64
s.bs([0x48, 0x8B, 0x45, 0x10, 0x48, 0x8B, 0x00])
"sys::strlen" => {
// (host addr : i64) -> i64
s.bs([
0x48, 0x8B, 0x7D, 0x10, 0x31, 0xC0, 0x48, 0xC7, 0xC1, 0xFF, 0xFF, 0xFF, 0xFF,
])
s.bs([0xF2, 0xAE, 0x48, 0xF7, 0xD1, 0x48, 0xFF, 0xC9, 0x48, 0x89, 0xC8])
}
"sys::copy_in" => {
// (dst guest i32, src host i64, n i32) -> ()
s.bs([0x8B, 0x7D, 0x20]) // mov edi,[rbp+32]
s.bs([0x48, 0x81, 0xC7])
s.i32(MEM_BASE)
s.bs([0x48, 0x8B, 0x75, 0x18]) // mov rsi,[rbp+24]
s.bs([0x8B, 0x4D, 0x10]) // mov ecx,[rbp+16]
s.bs([0xF3, 0xA4])
}
"wasi:cli/exit::exit" =>
// (status: result) -> () ; 0 = ok, 1 = err
s.bs([0x8B, 0x7D, 0x10, 0xB8, 0xE7, 0x00, 0x00, 0x00, 0x0F, 0x05])
_ => if !name.has_prefix("[resource-drop]") { return None }
}
s.bs([0x5D, 0xC3]) // pop rbp ; ret
Some(s)
}
///|
fn module_exports_prefix(m : Bytes, prefix : String) -> Bool raise CompileError {
let r = Reader::new(m, 8)
while r.pos < m.length() {
let id = r.byte()
let size = r.u32()
let end = r.pos + size
if id == 7 {
for _ in 0..<r.u32() {
let n = r.name()
ignore(r.byte())
ignore(r.u32())
if n.has_prefix(prefix) {
return true
}
}
}
r.pos = end
}
false
}
///|
/// Compile a WebAssembly core module (i32/i64/f32/f64 subset) or a component whose
/// core module targets `wasi:cli` 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[4] == b'\x0D' &&
wasm[6] == b'\x01' {
// Component: find the core module that exports wasi:cli/run.
let r = Reader::new(wasm, 8)
let mods : Array[Bytes] = []
while r.pos < wasm.length() {
let id = r.byte()
let size = r.u32()
if id == 1 {
mods.push(wasm[r.pos:r.pos + size].to_owned())
}
r.pos += size
}
for m in mods {
if module_exports_prefix(m, "wasi:cli/run@") {
return compile_core(m, entry)
}
}
raise CompileError("component has no core module exporting wasi:cli/run")
}
compile_core(wasm, entry)
}
///|
fn compile_core(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[Int32] = [] // function index space: imports first
let imports : Array[(String, String)] = []
let exports : Array[(String, Int32)] = []
let bodies : Array[(Int32, Int32)] = [] // (start of locals, end)
let globals : Array[Int64] = []
let mut mem_bytes = 0
let image : Array[Byte] = [] // initial contents of the RW segment (after globals page)
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_num(r)
}
let nr = r.u32()
if nr > 1 {
raise CompileError("multi-value results are not supported")
}
for _ in 0..<nr {
expect_num(r)
}
types.push({ nparams: np, nresults: nr, })
}
2 =>
for _ in 0..<r.u32() {
let m = r.name()
let n = r.name()
if r.byte() != 0 {
raise CompileError(
"only function imports are supported (\{m}::\{n})",
)
}
func_types.push(r.u32())
imports.push((m, n))
}
3 =>
for _ in 0..<r.u32() {
func_types.push(r.u32())
}
5 => {
if r.u32() != 1 {
raise CompileError("exactly one memory is supported")
}
let flags = r.byte()
let min = r.u32()
if flags == 1 {
ignore(r.u32())
}
if min > 16384 {
raise CompileError("memory too large (max 1 GiB)")
}
mem_bytes = min * 65536
}
6 =>
for _ in 0..<r.u32() {
expect_num(r)
ignore(r.byte()) // mutability
match r.byte() {
0x41 => globals.push(r.s32().to_int64())
0x42 => globals.push(r.s64())
0x43 => globals.push(r.raw32().to_int64() & 0xFFFFFFFFL)
0x44 => globals.push(r.raw64())
_ =>
raise CompileError("global initializers must be a numeric const")
}
if r.byte() != 0x0B {
raise CompileError("bad global initializer")
}
}
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
}
11 =>
for _ in 0..<r.u32() {
if r.u32() != 0 {
raise CompileError(
"only active data segments on memory 0 are supported",
)
}
if r.byte() != 0x41 {
raise CompileError("data offsets must be i32.const")
}
let off = r.s32()
if r.byte() != 0x0B {
raise CompileError("bad data offset expression")
}
let n = r.u32()
if off < 0 || off + n > mem_bytes {
raise CompileError("data segment out of bounds")
}
while image.length() < off + n {
image.push(b'\x00')
}
for i in 0..<n {
image[off + i] = r.byte().to_byte()
}
}
_ =>
raise CompileError(
"unsupported section id \{id} (tables, start, element segments are not supported)",
)
}
r.pos = end
}
let nimports = imports.length()
if bodies.length() != func_types.length() - nimports {
raise CompileError("function/code section length mismatch")
}
// choose entry
let find = fn(n : String) { exports.search_by(fn(e) { e.0 == n }) }
let entry_idx = match entry {
Some(n) =>
match find(n) {
Some(i) => exports[i].1
None => raise CompileError("no exported function named \{n}")
}
None =>
match find("_start") {
Some(i) => exports[i].1
None =>
match find("main") {
Some(i) => exports[i].1
None =>
match
exports.search_by(fn(e) { e.0.has_prefix("wasi:cli/run@") }) {
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 function bodies
let fns : Array[Fn] = []
for i in 0..<bodies.length() {
let (start, end) = bodies[i]
let ft = types[func_types[nimports + i]]
let br = Reader::new(wasm, start)
let mut nlocals = ft.nparams
for _ in 0..<br.u32() {
let count = br.u32()
expect_num(br)
nlocals += count
}
fns.push(
compile_body(
br,
end,
ft,
nlocals,
types,
func_types,
mem_bytes,
globals.length(),
),
)
}
// layout: _start | trap stubs | imports | functions | messages
let has_data = mem_bytes > 0 || globals.length() > 0
let phnum = if has_data { 2 } else { 1 }
let headers = 64 + 56 * phnum
let a = Asm::new()
if has_data {
a.bs([0x48, 0x89, 0x24, 0x25]) // mov [GLOB_BASE+0xFF8], rsp (argc/argv)
a.i32(GLOB_BASE + 0xFF8)
}
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[Int32] = []
let lea_at : Array[Int32] = []
for _ in 0..<messages.length() {
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[Int32] = []
for (m, n) in imports {
fn_at.push(a.here())
match import_stub(m, n) {
Some(s) =>
for c in s.code {
a.code.push(c)
}
None => raise CompileError("unsupported import \{m}::\{n}")
}
}
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[nimports + i] + at, fn_at[callee])
}
}
a.patch(start_call, fn_at[entry_idx])
for k in 0..<messages.length() {
let msg = messages[k]
a.patch(lea_at[k], a.here())
// fill `mov edx,len` imm32 right after the lea rel32
a.code[lea_at[k] + 4 + 1] = (msg.length() & 0xFF).to_byte()
for ch in msg {
a.code.push(ch.to_int().to_byte())
}
}
// ELF header + program headers
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, phnum, 2)
le(out, 0, 2)
le(out, 0, 2)
le(out, 0, 2)
let code_end = headers + a.here()
le(out, 1, 4) // PT_LOAD: code
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, code_end, 4)
le(out, 0, 4)
le(out, code_end, 4)
le(out, 0, 4)
le(out, 0x1000, 8)
let seg_off = (code_end + 0xFFF) / 0x1000 * 0x1000
let seg : Array[Byte] = []
if has_data {
// globals page, then initial memory contents
for _ in 0..<0x1000 {
seg.push(b'\x00')
}
for i in 0..<globals.length() {
for k in 0..<8 {
seg[8 * i + k] = ((globals[i] >> (8 * k)) & 0xFFL).to_int().to_byte()
}
}
for c in image {
seg.push(c)
}
le(out, 1, 4) // PT_LOAD: globals + linear memory
le(out, 6, 4) // R+W
le(out, seg_off, 8)
le(out, SEG_BASE, 4)
le(out, 0, 4)
le(out, SEG_BASE, 4)
le(out, 0, 4)
le(out, seg.length(), 4)
le(out, 0, 4)
le(out, 0x1000 + mem_bytes, 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)
}
if has_data {
while out.length() < seg_off {
out.push(b'\x00')
}
for c in seg {
out.push(c)
}
}
Bytes::from_array(out)
}