Add wasi:cli component support, linear memory and globals

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
nandiandClaude Sonnet 5.5 committed 2026-11-21 01:03:32 -08:00
1 parent cb1cec8b13
commit 05488c9783
11 files changed
+513 -47

No files matched your search

+28 -13
View File
@@ -1,21 +1,36 @@
# wasm2elf
A WebAssembly → static x86-64 Linux ELF compiler, written in MoonBit. No C, no LLVM, no
runtime: the output is a single `PT_LOAD` segment with hand-encoded machine code.
runtime: the output is hand-encoded machine code in one or two `PT_LOAD` segments.
```
wasm-tools parse examples/shine_rise.wat -o shine_rise.wasm
moon build --target native
_build/native/debug/build/cmd/main/main.exe shine_rise.wasm shine_rise [entry-export]
./shine_rise # wasm trap: unreachable (exit 134)
just run sum # core module -> ELF, runs it, prints the exit code
just run-component hello # wasi:cli component -> ELF, prints "Hello from wasi:cli!"
just examples # everything in examples/
```
The entry export (default `_start`, then `main`, then the first function export) is called
from `_start`; its i32 result becomes the exit code. Traps print a message to stderr and
exit 134.
By hand: `wasm2elf <input.wasm> <output> [entry-export]`. The input can be a core module or
a component; for a component, the core module exporting `wasi:cli/run@…#run` is compiled.
Supported: i32 only; locals, params, calls, block/loop/if/else/br/br_if/return,
select/drop, all i32 arithmetic/comparison/shift/rotate ops, divide-by-zero and
INT_MIN/-1 traps. Not supported: i64/floats, memory, globals, tables, imports, br_table.
Input is assumed valid (`wasm-tools validate` it first). `./run_examples.sh` builds and
runs everything in `examples/`.
The entry export (default `_start`, then `main`, then `wasi:cli/run@…`, then the first
function export) is called from `_start`; its i32 result becomes the exit code. Traps
(`unreachable`, divide by zero, overflow, out-of-bounds memory) print a message to stderr
and exit 134.
## wasi:cli
The core module of a component imports lowered `wasi:cli` / `wasi:io` functions by name.
They are implemented as small native stubs (no host runtime): `wasi:cli/stdout.get-stdout`,
`stderr.get-stderr`, `stdin.get-stdin` (handles are fds 1/2/0),
`wasi:io/streams [method]output-stream.blocking-write-and-flush` (a `write(2)` syscall),
`wasi:cli/exit.exit`, and `[resource-drop]*` (no-op). Anything else is a compile error.
`examples/wit` holds minimal WIT for these interfaces so `wasm-tools component embed/new`
can build the example.
## Supported subset
i32 only; locals, params, calls, block/loop/if/else/br/br_if/return, select/drop, i32
arithmetic/comparison/shift/rotate, one fixed-size linear memory (i32 loads/stores with
bounds checks, `memory.size`; `memory.grow` always returns -1), i32 globals, active data
segments. Not supported: i64/floats, tables/`call_indirect`, `br_table`, start function,
non-function imports. Input is assumed valid (`wasm-tools validate` it first).
+12
View File
@@ -0,0 +1,12 @@
// Generated using `moon info`, DON'T EDIT IT
package "nandi/wasm2elf/cmd/main"
// Values
// Errors
// Types and methods
// Type aliases
// Traits
+92 -1
View File
@@ -20,6 +20,8 @@ priv struct Fn {
code : Asm
ft : FuncType
nlocals : Int // total locals including params
mem_bytes : Int
nglobals : Int
frames : Array[Frame]
calls : Array[(Int, Int)] // (rel32 position, callee function index)
traps : Array[(Int, Int)] // (rel32 position, trap kind)
@@ -36,6 +38,9 @@ const TRAP_DIV_ZERO : Int = 1
///|
const TRAP_OVERFLOW : Int = 2
///|
const TRAP_OOB : Int = 3
///|
fn Fn::push_rax(self : Fn) -> Unit {
self.code.b(0x50)
@@ -166,6 +171,57 @@ fn Fn::divrem(self : Fn, op : Int) -> Unit {
self.push_rax()
}
///|
/// Linear-memory load/store: bounds check, then access at MEM_BASE + addr + offset.
fn Fn::mem_access(self : Fn, r : Reader, op : Int) -> Unit raise CompileError {
ignore(r.u32()) // alignment hint
let offset = r.u32()
if self.mem_bytes == 0 {
raise CompileError("memory access but the module defines no memory")
}
if offset < 0 {
raise CompileError("memory offset too large")
}
let size = match op {
0x28 | 0x36 => 4
0x2C | 0x2D | 0x3A => 1
_ => 2
}
let is_store = op >= 0x36
if is_store {
self.pop(1)
}
self.pop(0)
self.code.bs([0x89, 0xC0]) // mov eax,eax (zero-extend address)
self.code.bs([0x48, 0x05]) // add rax, offset
self.code.i32(offset)
self.code.bs([0x48, 0x3D]) // cmp rax, mem_bytes - size
self.code.i32(self.mem_bytes - size)
self.trap_jmp(TRAP_OOB, [0x0F, 0x87]) // ja trap
match op {
0x28 => self.code.bs([0x8B, 0x80])
0x2C => self.code.bs([0x0F, 0xBE, 0x80])
0x2D => self.code.bs([0x0F, 0xB6, 0x80])
0x2E => self.code.bs([0x0F, 0xBF, 0x80])
0x2F => self.code.bs([0x0F, 0xB7, 0x80])
0x36 => self.code.bs([0x89, 0x88])
0x3A => self.code.bs([0x88, 0x88])
_ => self.code.bs([0x66, 0x89, 0x88])
}
self.code.i32(MEM_BASE)
if !is_store {
self.push_rax()
}
}
///|
fn Fn::global_addr(self : Fn, idx : Int) -> Int raise CompileError {
if idx < 0 || idx >= self.nglobals {
raise CompileError("global index out of range")
}
GLOB_BASE + 8 * idx
}
///|
/// Compile one function body. Returns the generated Fn (machine code + patch lists).
fn compile_body(
@@ -175,11 +231,15 @@ fn compile_body(
nlocals : Int,
all_types : Array[FuncType],
func_types : Array[Int],
mem_bytes : Int,
nglobals : Int,
) -> Fn raise CompileError {
let f : Fn = {
code: Asm::new(),
ft,
nlocals,
mem_bytes,
nglobals,
frames: [],
calls: [],
traps: [],
@@ -238,8 +298,13 @@ fn compile_body(
}
}
}
0x0C | 0x0D | 0x10 | 0x20 | 0x21 | 0x22 => ignore(r.u32())
0x0C | 0x0D | 0x10 | 0x20 | 0x21 | 0x22 | 0x23 | 0x24 => ignore(r.u32())
0x41 => ignore(r.s32())
0x3F | 0x40 => ignore(r.byte())
n if n >= 0x28 && n <= 0x3E => {
ignore(r.u32())
ignore(r.u32())
}
_ => ()
}
continue
@@ -342,6 +407,32 @@ fn compile_body(
f.code.bs([0x48, 0x89, 0x85])
f.code.i32(d)
}
0x23 => {
let a = f.global_addr(r.u32())
f.code.bs([0x8B, 0x04, 0x25]) // mov eax,[abs]
f.code.i32(a)
f.push_rax()
}
0x24 => {
let a = f.global_addr(r.u32())
f.pop(0)
f.code.bs([0x89, 0x04, 0x25]) // mov [abs],eax
f.code.i32(a)
}
0x28 | 0x2C | 0x2D | 0x2E | 0x2F | 0x36 | 0x3A | 0x3B => f.mem_access(r, op)
0x3F => {
ignore(r.byte())
f.code.b(0x68)
f.code.i32(f.mem_bytes / 65536)
f.height += 1
}
0x40 => {
// memory is fixed-size: memory.grow always fails (-1)
ignore(r.byte())
f.pop(0)
f.code.bs([0x6A, 0xFF])
f.height += 1
}
0x41 => {
f.code.b(0x68)
f.code.i32(r.s32())
+16
View File
@@ -0,0 +1,16 @@
;; Core module for a wasi:cli/command component.
;; Build with: just run-component hello
(module
(import "wasi:cli/stdout@0.2.0" "get-stdout" (func $get_stdout (result i32)))
(import "wasi:io/streams@0.2.0" "[method]output-stream.blocking-write-and-flush"
(func $write (param i32 i32 i32 i32)))
(memory (export "memory") 1)
(data (i32.const 16) "Hello from wasi:cli!\0a")
(func (export "wasi:cli/run@0.2.0#run") (result i32)
(call $write
(call $get_stdout) ;; self: output-stream handle
(i32.const 16) ;; ptr
(i32.const 21) ;; len
(i32.const 64)) ;; retptr for result<_, stream-error>
(i32.load8_u (i32.const 64)))) ;; 0 = ok -> exit code 0
+17
View File
@@ -0,0 +1,17 @@
;; globals + linear memory: stores, sign/zero-extending loads, then an OOB trap
(module
(memory 1)
(global $g (mut i32) (i32.const 40))
(data (i32.const 0) "\ff\01")
(func (export "main") (result i32)
(global.set $g (i32.add (global.get $g) (i32.const 1)))
(i32.store (i32.const 100) (i32.const 0x01020304))
(if (i32.ne (i32.load8_u (i32.const 100)) (i32.const 4)) (then (return (i32.const 1))))
(if (i32.ne (i32.load8_s (i32.const 0)) (i32.const -1)) (then (return (i32.const 2))))
(if (i32.ne (i32.load16_u (i32.const 0)) (i32.const 0x01ff)) (then (return (i32.const 3))))
(i32.store8 (i32.const 200) (i32.const 1))
(global.set $g (i32.add (global.get $g) (i32.load8_u (i32.const 200))))
(if (i32.ne (memory.size) (i32.const 1)) (then (return (i32.const 4))))
(if (i32.ne (global.get $g) (i32.const 42)) (then (return (i32.const 5))))
(drop (i32.load (i32.const 65533))) ;; 4-byte load straddling the end: traps
(global.get $g)))
+26
View File
@@ -0,0 +1,26 @@
package wasi:cli@0.2.0;
interface stdout {
use wasi:io/streams@0.2.0.{output-stream};
get-stdout: func() -> output-stream;
}
interface stderr {
use wasi:io/streams@0.2.0.{output-stream};
get-stderr: func() -> output-stream;
}
interface exit {
exit: func(status: result);
}
interface run {
run: func() -> result;
}
world command {
import stdout;
import stderr;
import exit;
export run;
}
+18
View File
@@ -0,0 +1,18 @@
package wasi:io@0.2.0;
interface error {
resource error {}
}
interface streams {
use error.{error};
variant stream-error {
last-operation-failed(error),
closed,
}
resource output-stream {
blocking-write-and-flush: func(contents: list<u8>) -> result<_, stream-error>;
}
}
+5
View File
@@ -0,0 +1,5 @@
package local:examples;
world hello {
include wasi:cli/command@0.2.0;
}
+12
View File
@@ -23,6 +23,18 @@ compile name: build
run name: (compile name)
-./out/{{name}}; echo "exit code: $?"
# compile a wasi:cli component example (examples/<name>.wat + examples/wit, world <name>) to out/<name>
component name: build
mkdir -p out
wasm-tools component embed examples/wit examples/{{name}}.wat --world {{name}} -o out/{{name}}.embed.wasm
wasm-tools component new out/{{name}}.embed.wasm -o out/{{name}}.wasm
wasm-tools validate out/{{name}}.wasm
{{exe}} out/{{name}}.wasm out/{{name}}
# compile and run a wasi:cli component example
run-component name: (component name)
-./out/{{name}}; echo "exit code: $?"
# build and run every example
examples: build
./run_examples.sh
+271 -33
View File
@@ -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,29 +237,56 @@ 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 =>
match exports.search_by(fn(e) { e.0.has_prefix("wasi:cli/run@") }) {
Some(i) => exports[i].1
None =>
if exports.length() > 0 {
@@ -118,25 +298,39 @@ pub fn compile(wasm : Bytes, entry : String?) -> Bytes raise CompileError {
}
}
}
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)
}
+16
View File
@@ -0,0 +1,16 @@
// Generated using `moon info`, DON'T EDIT IT
package "nandi/wasm2elf"
// Values
pub fn compile(Bytes, String?) -> Bytes raise CompileError
// Errors
pub suberror CompileError {
CompileError(String)
}
// Types and methods
// Type aliases
// Traits