///| 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..> (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.. 1 { raise CompileError("multi-value results are not supported") } for _ in 0.. for _ in 0.. for _ in 0.. for _ in 0.. 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..