Add wasi:cli component support, linear memory and globals
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
cb1cec8b13
commit
05488c9783
11 files changed
+518
-52
No files matched your search
+276
-38
@@ -2,14 +2,17 @@
|
||||
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)})")
|
||||
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 {
|
||||
// little-endian, zero-extended past 32 bits (Int shifts wrap mod 32)
|
||||
for i in 0..<n {
|
||||
out.push(((v >> (8 * i)) & 0xFF).to_byte())
|
||||
out.push(if i < 4 { ((v >> (8 * i)) & 0xFF).to_byte() } else { b'\x00' })
|
||||
}
|
||||
}
|
||||
|
||||
@@ -17,18 +20,126 @@ fn le(out : Array[Byte], v : Int, n : Int) -> Unit {
|
||||
const BASE : Int = 0x400000
|
||||
|
||||
///|
|
||||
const HEADERS : Int = 120
|
||||
/// Read/write data segment: one page of globals, then linear memory.
|
||||
const SEG_BASE : Int = 0x10000000
|
||||
|
||||
///|
|
||||
const GLOB_BASE : Int = 0x10000000
|
||||
|
||||
///|
|
||||
const MEM_BASE : Int = 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",
|
||||
]
|
||||
|
||||
///|
|
||||
/// 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.
|
||||
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)
|
||||
}
|
||||
"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-only 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' ||
|
||||
@@ -38,9 +149,13 @@ pub fn compile(wasm : Bytes, entry : String?) -> Bytes raise CompileError {
|
||||
}
|
||||
let r = Reader::new(wasm, 8)
|
||||
let types : Array[FuncType] = []
|
||||
let func_types : Array[Int] = []
|
||||
let func_types : Array[Int] = [] // function index space: imports first
|
||||
let imports : Array[(String, String)] = []
|
||||
let exports : Array[(String, Int)] = []
|
||||
let bodies : Array[(Int, Int)] = [] // (start of locals, end)
|
||||
let globals : Array[Int] = []
|
||||
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()
|
||||
@@ -65,10 +180,48 @@ pub fn compile(wasm : Bytes, entry : String?) -> Bytes raise CompileError {
|
||||
}
|
||||
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_i32(r)
|
||||
ignore(r.byte()) // mutability
|
||||
if r.byte() != 0x41 {
|
||||
raise CompileError("global initializers must be i32.const")
|
||||
}
|
||||
globals.push(r.s32())
|
||||
if r.byte() != 0x0B {
|
||||
raise CompileError("bad global initializer")
|
||||
}
|
||||
}
|
||||
7 =>
|
||||
for _ in 0..<r.u32() {
|
||||
let name = r.name()
|
||||
@@ -84,59 +237,100 @@ pub fn compile(wasm : Bytes, entry : String?) -> Bytes raise CompileError {
|
||||
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} (imports, tables, memory, globals, start, data are not supported)",
|
||||
"unsupported section id \{id} (tables, start, element segments are not supported)",
|
||||
)
|
||||
}
|
||||
r.pos = end
|
||||
}
|
||||
if bodies.length() != func_types.length() {
|
||||
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 exports.search_by(fn(e) { e.0 == n }) {
|
||||
match find(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") {
|
||||
None =>
|
||||
match find("_start") {
|
||||
Some(i) => exports[i].1
|
||||
None =>
|
||||
match pick("main") {
|
||||
match find("main") {
|
||||
Some(i) => exports[i].1
|
||||
None =>
|
||||
if exports.length() > 0 {
|
||||
exports[0].1
|
||||
} else {
|
||||
raise CompileError("module exports no functions")
|
||||
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 {
|
||||
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
|
||||
// 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 = types[func_types[i]].nparams
|
||||
let mut nlocals = ft.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),
|
||||
compile_body(
|
||||
br,
|
||||
end,
|
||||
ft,
|
||||
nlocals,
|
||||
types,
|
||||
func_types,
|
||||
mem_bytes,
|
||||
globals.length(),
|
||||
),
|
||||
)
|
||||
}
|
||||
// layout: _start | trap stubs | functions | messages
|
||||
// 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()
|
||||
let start_call = a.rel([0xE8])
|
||||
a.bs([0x89, 0xC7]) // mov edi,eax
|
||||
@@ -146,7 +340,7 @@ pub fn compile(wasm : Bytes, entry : String?) -> Bytes raise CompileError {
|
||||
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 {
|
||||
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)
|
||||
@@ -157,6 +351,16 @@ pub fn compile(wasm : Bytes, entry : String?) -> Bytes raise CompileError {
|
||||
a.bs([0xB8, 0xE7, 0x00, 0x00, 0x00, 0x0F, 0x05]) // exit_group
|
||||
}
|
||||
let fn_at : Array[Int] = []
|
||||
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)
|
||||
@@ -170,22 +374,20 @@ pub fn compile(wasm : Bytes, entry : String?) -> Bytes raise CompileError {
|
||||
// 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(fn_at[nimports + i] + at, fn_at[callee])
|
||||
}
|
||||
}
|
||||
a.patch(start_call, fn_at[entry_idx])
|
||||
for k in 0..<3 {
|
||||
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
|
||||
let imm = lea_at[k] + 4 + 1
|
||||
let n = msg.length()
|
||||
a.code[imm] = (n & 0xFF).to_byte()
|
||||
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 + one PT_LOAD program header
|
||||
// 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())
|
||||
@@ -193,7 +395,7 @@ pub fn compile(wasm : Bytes, entry : String?) -> Bytes raise CompileError {
|
||||
le(out, 2, 2) // ET_EXEC
|
||||
le(out, 0x3E, 2) // x86-64
|
||||
le(out, 1, 4)
|
||||
le(out, BASE + HEADERS, 4)
|
||||
le(out, BASE + headers, 4)
|
||||
le(out, 0, 4) // entry (high)
|
||||
le(out, 64, 4) // phoff
|
||||
le(out, 0, 4)
|
||||
@@ -201,28 +403,64 @@ pub fn compile(wasm : Bytes, entry : String?) -> Bytes raise CompileError {
|
||||
le(out, 0, 4) // flags
|
||||
le(out, 64, 2)
|
||||
le(out, 56, 2)
|
||||
le(out, 1, 2)
|
||||
le(out, phnum, 2)
|
||||
le(out, 0, 2)
|
||||
le(out, 0, 2)
|
||||
le(out, 0, 2)
|
||||
let total = HEADERS + a.here()
|
||||
le(out, 1, 4) // PT_LOAD
|
||||
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, total, 4)
|
||||
le(out, code_end, 4)
|
||||
le(out, 0, 4)
|
||||
le(out, total, 4)
|
||||
le(out, code_end, 4)
|
||||
le(out, 0, 4)
|
||||
le(out, 0x1000, 8)
|
||||
while out.length() < HEADERS {
|
||||
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..<4 {
|
||||
seg[8 * i + k] = ((globals[i] >> (8 * k)) & 0xFF).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)
|
||||
}
|
||||
Reference in new issue
Block a user