///| 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..> (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) } "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.. 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.. 1 { raise CompileError("multi-value results are not supported") } for _ in 0.. for _ in 0.. for _ in 0.. { 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.. 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.. for _ in 0.. for _ in 0.. mem_bytes { raise CompileError("data segment out of bounds") } while image.length() < off + n { image.push(b'\x00') } for i in 0.. 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.. 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 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.. 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..> (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) }