Files
wasm2elf-mb/asm.mbt
T

60 lines
1.1 KiB
MoonBit

///|
/// Growable x86-64 machine-code buffer with rel32 patching helpers.
priv struct Asm {
code : Array[Byte]
}
///|
fn Asm::new() -> Asm {
{ code: [] }
}
///|
fn Asm::here(self : Asm) -> Int {
self.code.length()
}
///|
fn Asm::b(self : Asm, x : Int) -> Unit {
self.code.push((x & 0xFF).to_byte())
}
///|
fn Asm::bs(self : Asm, xs : Array[Int]) -> Unit {
for x in xs {
self.b(x)
}
}
///|
fn Asm::i32(self : Asm, x : Int) -> Unit {
self.b(x)
self.b(x >> 8)
self.b(x >> 16)
self.b(x >> 24)
}
///|
/// Emit opcode bytes followed by a rel32 placeholder; returns the placeholder's position.
fn Asm::rel(self : Asm, op : Array[Int]) -> Int {
self.bs(op)
let at = self.here()
self.i32(0)
at
}
///|
/// Point the rel32 placeholder at `at` to `target`.
fn Asm::patch(self : Asm, at : Int, target : Int) -> Unit {
let v = target - (at + 4)
self.code[at] = (v & 0xFF).to_byte()
self.code[at + 1] = ((v >> 8) & 0xFF).to_byte()
self.code[at + 2] = ((v >> 16) & 0xFF).to_byte()
self.code[at + 3] = ((v >> 24) & 0xFF).to_byte()
}
///|
fn Asm::patch_here(self : Asm, at : Int) -> Unit {
self.patch(at, self.here())
}