From b8617c7aaa925ef3248ce69cac253f848485a751 Mon Sep 17 00:00:00 2001 From: nandithebull Date: Sat, 21 Nov 2026 00:53:04 -0800 Subject: [PATCH] Add wasm2elf: i32 WebAssembly to static x86-64 ELF compiler in MoonBit Co-Authored-By: Claude Sonnet 5.5 --- .githooks/README.md | 21 ++ .githooks/pre-commit | 3 + .github/workflows/copilot-setup-steps.yml | 41 +++ .gitignore | 6 + AGENTS.md | 53 +++ LICENSE | 202 ++++++++++++ README.mbt.md | 21 ++ README.md | 1 + asm.mbt | 59 ++++ cmd/main/main.mbt | 25 ++ cmd/main/moon.pkg | 11 + compile.mbt | 381 ++++++++++++++++++++++ examples/divzero.wat | 3 + examples/fact.wat | 8 + examples/misc.wat | 16 + examples/shine_rise.wat | 15 + examples/sum.wat | 12 + module.mbt | 228 +++++++++++++ moon.mod | 26 ++ moon.pkg | 0 reader.mbt | 75 +++++ run_examples.sh | 12 + 22 files changed, 1219 insertions(+) create mode 100644 .githooks/README.md create mode 100755 .githooks/pre-commit create mode 100644 .github/workflows/copilot-setup-steps.yml create mode 100644 .gitignore create mode 100644 AGENTS.md create mode 100644 LICENSE create mode 100644 README.mbt.md create mode 120000 README.md create mode 100644 asm.mbt create mode 100644 cmd/main/main.mbt create mode 100644 cmd/main/moon.pkg create mode 100644 compile.mbt create mode 100644 examples/divzero.wat create mode 100644 examples/fact.wat create mode 100644 examples/misc.wat create mode 100644 examples/shine_rise.wat create mode 100644 examples/sum.wat create mode 100644 module.mbt create mode 100644 moon.mod create mode 100644 moon.pkg create mode 100644 reader.mbt create mode 100755 run_examples.sh diff --git a/.githooks/README.md b/.githooks/README.md new file mode 100644 index 0000000..61c0ad6 --- /dev/null +++ b/.githooks/README.md @@ -0,0 +1,21 @@ +# Git Hooks + +## Pre-commit Hook + +This pre-commit hook performs automatic checks before finalizing your commit. + +### Usage Instructions + +To use this pre-commit hook: + +1. Make the hook executable if it isn't already: + ```bash + chmod +x .githooks/pre-commit + ``` + +2. Configure Git to use the hooks in the .githooks directory: + ```bash + git config core.hooksPath .githooks + ``` + +3. The hook will automatically run when you execute `git commit` diff --git a/.githooks/pre-commit b/.githooks/pre-commit new file mode 100755 index 0000000..e2a32b0 --- /dev/null +++ b/.githooks/pre-commit @@ -0,0 +1,3 @@ +#!/bin/sh + +moon check \ No newline at end of file diff --git a/.github/workflows/copilot-setup-steps.yml b/.github/workflows/copilot-setup-steps.yml new file mode 100644 index 0000000..6f8811a --- /dev/null +++ b/.github/workflows/copilot-setup-steps.yml @@ -0,0 +1,41 @@ +# Reference: https://docs.github.com/en/copilot/how-tos/use-copilot-agents/coding-agent/customize-the-agent-environment +name: "Copilot Setup Steps" + +# Automatically run the setup steps when they are changed to allow for easy validation, and +# allow manual testing through the repository's "Actions" tab +on: + workflow_dispatch: + push: + paths: + - .github/workflows/copilot-setup-steps.yml + pull_request: + paths: + - .github/workflows/copilot-setup-steps.yml + +jobs: + # The job MUST be called `copilot-setup-steps` or it will not be picked up by Copilot. + copilot-setup-steps: + runs-on: ubuntu-latest + + # Set the permissions to the lowest permissions possible needed for your steps. + # Copilot will be given its own token for its operations. + permissions: + # If you want to clone the repository as part of your setup steps, for example to install dependencies, you'll need the `contents: read` permission. If you don't clone the repository in your setup steps, Copilot will do this for you automatically after the steps complete. + contents: read + + # You can define any steps you want, and they will run before the agent starts. + # If you do not check out your code, Copilot will do this for you. + steps: + - name: Checkout code + uses: actions/checkout@v5 + + - name: Set up MoonBit + run: | + curl -fsSL https://cli.moonbitlang.com/install/unix.sh | bash + echo "$HOME/.moon/bin" >> $GITHUB_PATH + + - name: Update MoonBit dependencies + run: | + moon version --all + moon update + diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..590f40a --- /dev/null +++ b/.gitignore @@ -0,0 +1,6 @@ +.DS_Store +_build/ +target/ +target +.mooncakes/ +.moonagent/out/ diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..c0e8474 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,53 @@ +# Project Agents.md Guide + +This is a [MoonBit](https://docs.moonbitlang.com) project. + +You can browse and install extra skills here: + + +## Project Structure + +- MoonBit packages are organized per directory; each directory contains a + `moon.pkg` file listing its dependencies. Each package has its files and + blackbox test files (ending in `_test.mbt`) and whitebox test files (ending in + `_wbtest.mbt`). + +- In the toplevel directory, there is a `moon.mod` file listing module + metadata. + +## Coding convention + +- MoonBit code is organized in block style, each block is separated by `///|`, + the order of each block is irrelevant. In some refactorings, you can process + block by block independently. + +- Try to keep deprecated blocks in file called `deprecated.mbt` in each + directory. + +## Tooling + +- `moon fmt` is used to format your code properly. + +- `moon ide` provides project navigation helpers like `peek-def`, `outline`, and + `find-references`. See $moonbit-agent-guide for details. + +- `moon info` is used to update the generated interface of the package, each + package has a generated interface file `.mbti`, it is a brief formal + description of the package. If nothing in `.mbti` changes, this means your + change does not bring the visible changes to the external package users, it is + typically a safe refactoring. + +- In the last step, run `moon info && moon fmt` to update the interface and + format the code. Check the diffs of `.mbti` file to see if the changes are + expected. + +- Run `moon test` to check tests pass. MoonBit supports snapshot testing; when + changes affect outputs, run `moon test --update` to refresh snapshots. + +- Prefer `assert_eq` or `assert_true(pattern is Pattern(...))` for results that + are stable or very unlikely to change. For snapshot tests that record + structured debugging output, derive `Debug` and use `debug_inspect`, rather + than deriving `Show` for debugging. For solid, well-defined results (e.g. + scientific computations), prefer assertion tests. You can use + `moon coverage analyze > uncovered.log` to see which parts of your code are + not covered by tests. diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..d645695 --- /dev/null +++ b/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/README.mbt.md b/README.mbt.md new file mode 100644 index 0000000..286a4f0 --- /dev/null +++ b/README.mbt.md @@ -0,0 +1,21 @@ +# 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. + +``` +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) +``` + +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. + +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/`. diff --git a/README.md b/README.md new file mode 120000 index 0000000..7ae1db3 --- /dev/null +++ b/README.md @@ -0,0 +1 @@ +README.mbt.md \ No newline at end of file diff --git a/asm.mbt b/asm.mbt new file mode 100644 index 0000000..8ac60f3 --- /dev/null +++ b/asm.mbt @@ -0,0 +1,59 @@ +///| +/// 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()) +} diff --git a/cmd/main/main.mbt b/cmd/main/main.mbt new file mode 100644 index 0000000..18fe624 --- /dev/null +++ b/cmd/main/main.mbt @@ -0,0 +1,25 @@ +///| +async fn main { + let args = @env.args() + // args[0] is the program name + if args.length() < 3 { + println("usage: wasm2elf [entry-export]") + @env.exit(2) + } + let wasm = @fs.read_binary(args[1]) + let entry : String? = if args.length() > 3 { Some(args[3]) } else { None } + try { + let elf = @lib.compile(wasm, entry) + @fs.write_binary(args[2], elf, permission=0o755) + println("wrote \{args[2]} (\{elf.length()} bytes)") + } catch { + @lib.CompileError(msg) => { + println("error: \{msg}") + @env.exit(1) + } + err => { + println("error: \{err}") + @env.exit(1) + } + } +} diff --git a/cmd/main/moon.pkg b/cmd/main/moon.pkg new file mode 100644 index 0000000..c431b84 --- /dev/null +++ b/cmd/main/moon.pkg @@ -0,0 +1,11 @@ +import { + "nandi/wasm2elf" @lib, + "moonbitlang/core/async/fs" @fs, + "moonbitlang/core/async", + "moonbitlang/core/env", +} + +options( + "is-main": true, + "allow-experimental-packages": ["moonbitlang/core/async/fs", "moonbitlang/core/async"], +) diff --git a/compile.mbt b/compile.mbt new file mode 100644 index 0000000..f5a210c --- /dev/null +++ b/compile.mbt @@ -0,0 +1,381 @@ +///| +priv struct FuncType { + nparams : Int + nresults : Int +} + +///| +priv struct Frame { + kind : Int // 0 = block, 1 = loop, 2 = if + base : Int + arity : Int + skip : Bool // opened while unreachable: emits nothing + loop_start : Int + ends : Array[Int] + mut else_patch : Int +} + +///| +priv struct Fn { + code : Asm + ft : FuncType + nlocals : Int // total locals including params + frames : Array[Frame] + calls : Array[(Int, Int)] // (rel32 position, callee function index) + traps : Array[(Int, Int)] // (rel32 position, trap kind) + mut height : Int + mut dead : Bool +} + +///| +const TRAP_UNREACHABLE : Int = 0 + +///| +const TRAP_DIV_ZERO : Int = 1 + +///| +const TRAP_OVERFLOW : Int = 2 + +///| +fn Fn::push_rax(self : Fn) -> Unit { + self.code.b(0x50) + self.height += 1 +} + +///| +fn Fn::pop(self : Fn, reg : Int) -> Unit { + // reg: 0 = rax, 1 = rcx, 2 = rdx + self.code.b(0x58 + reg) + self.height -= 1 +} + +///| +fn Fn::add_rsp(self : Fn, slots : Int) -> Unit { + if slots > 0 { + self.code.bs([0x48, 0x81, 0xC4]) + self.code.i32(slots * 8) + } +} + +///| +fn Fn::local_disp(self : Fn, idx : Int) -> Int raise CompileError { + if idx < 0 || idx >= self.nlocals { + raise CompileError("local index out of range") + } + let np = self.ft.nparams + if idx < np { + 16 + (np - 1 - idx) * 8 + } else { + -8 * (idx - np + 1) + } +} + +///| +fn Fn::trap_jmp(self : Fn, kind : Int, cond : Array[Int]) -> Unit { + let at = self.code.rel(cond) + self.traps.push((at, kind)) +} + +///| +fn Fn::emit_br(self : Fn, depth : Int, h : Int) -> Unit raise CompileError { + if depth >= self.frames.length() { + raise CompileError("branch depth out of range") + } + let f = self.frames[self.frames.length() - 1 - depth] + let arity = if f.kind == 1 { 0 } else { f.arity } + if arity == 1 { + self.code.b(0x58) // pop rax + self.add_rsp(h - 1 - f.base) + self.code.b(0x50) // push rax + } else { + self.add_rsp(h - f.base) + } + if f.kind == 1 { + let at = self.code.rel([0xE9]) + self.code.patch(at, f.loop_start) + } else { + f.ends.push(self.code.rel([0xE9])) + } +} + +///| +fn Fn::block_type(r : Reader) -> Int raise CompileError { + match r.byte() { + 0x40 => 0 + 0x7F => 1 + b => raise CompileError("unsupported block type 0x\{b.to_string(radix=16)}") + } +} + +///| +fn Fn::open( + self : Fn, + kind : Int, + arity : Int, + skip : Bool, +) -> Unit { + self.frames.push({ + kind, + base: self.height, + arity, + skip, + loop_start: self.code.here(), + ends: [], + else_patch: -1, + }) +} + +///| +fn Fn::binop(self : Fn, op : Array[Int]) -> Unit { + self.pop(1) + self.pop(0) + self.code.bs(op) + self.push_rax() +} + +///| +fn Fn::cmp(self : Fn, setcc : Int) -> Unit { + self.pop(1) + self.pop(0) + self.code.bs([0x39, 0xC8, 0x0F, setcc, 0xC0, 0x0F, 0xB6, 0xC0]) + self.push_rax() +} + +///| +fn Fn::divrem(self : Fn, op : Int) -> Unit { + // op: 0x6D div_s, 0x6E div_u, 0x6F rem_s, 0x70 rem_u + self.pop(1) + self.pop(0) + self.trap_jmp(TRAP_DIV_ZERO, [0x85, 0xC9, 0x0F, 0x84]) // test ecx,ecx ; jz + match op { + 0x6D => { + self.code.bs([0x83, 0xF9, 0xFF, 0x75, 0x0B]) // cmp ecx,-1 ; jne L + self.code.bs([0x3D, 0x00, 0x00, 0x00, 0x80]) // cmp eax,INT_MIN + let at = self.code.rel([0x0F, 0x84]) + self.traps.push((at, TRAP_OVERFLOW)) + self.code.bs([0x99, 0xF7, 0xF9]) // L: cdq ; idiv ecx + } + 0x6E => self.code.bs([0x31, 0xD2, 0xF7, 0xF1]) // xor edx,edx ; div ecx + 0x6F => { + self.code.bs([0x83, 0xF9, 0xFF, 0x75, 0x04]) // cmp ecx,-1 ; jne L + self.code.bs([0x31, 0xC0, 0xEB, 0x05]) // xor eax,eax ; jmp done + self.code.bs([0x99, 0xF7, 0xF9, 0x89, 0xD0]) // L: cdq ; idiv ecx ; mov eax,edx + } + _ => self.code.bs([0x31, 0xD2, 0xF7, 0xF1, 0x89, 0xD0]) // xor edx,edx ; div ecx ; mov eax,edx + } + self.push_rax() +} + +///| +/// Compile one function body. Returns the generated Fn (machine code + patch lists). +fn compile_body( + r : Reader, + body_end : Int, + ft : FuncType, + nlocals : Int, + all_types : Array[FuncType], + func_types : Array[Int], +) -> Fn raise CompileError { + let f : Fn = { + code: Asm::new(), + ft, + nlocals, + frames: [], + calls: [], + traps: [], + height: 0, + dead: false, + } + // prologue: push rbp ; mov rbp,rsp ; zero-init non-param locals + f.code.bs([0x55, 0x48, 0x89, 0xE5]) + for _ in 0..<(nlocals - ft.nparams) { + f.code.bs([0x6A, 0x00]) + } + f.open(0, ft.nresults, false) + let mut finished = false + while !finished { + if r.pos >= body_end { + raise CompileError("function body missing end") + } + let op = r.byte() + let skipping = f.frames[f.frames.length() - 1].skip + let dead = f.dead + if skipping || dead { + // Unreachable code: parse immediates, only track control structure. + match op { + 0x02 | 0x03 | 0x04 => { + let a = Fn::block_type(r) + f.open(if op == 0x03 { 1 } else if op == 0x04 { 2 } else { 0 }, a, true) + } + 0x05 => { + if !skipping { + let fr = f.frames[f.frames.length() - 1] + if fr.else_patch >= 0 { + f.code.patch_here(fr.else_patch) + fr.else_patch = -1 + } + f.height = fr.base + f.dead = false + } + } + 0x0B => { + let fr = f.frames.pop().unwrap() + if !fr.skip { + if fr.else_patch >= 0 { + f.code.patch_here(fr.else_patch) + } + for e in fr.ends { + f.code.patch_here(e) + } + f.height = fr.base + fr.arity + f.dead = false + if f.frames.length() == 0 { + if ft.nresults == 1 { + f.code.b(0x58) + } + f.code.bs([0xC9, 0xC3]) + finished = true + } + } + } + 0x0C | 0x0D | 0x10 | 0x20 | 0x21 | 0x22 => ignore(r.u32()) + 0x41 => ignore(r.s32()) + _ => () + } + continue + } + match op { + 0x00 => { + f.trap_jmp(TRAP_UNREACHABLE, [0xE9]) + f.dead = true + } + 0x01 => () + 0x02 | 0x03 | 0x04 => { + let a = Fn::block_type(r) + if op == 0x04 { + f.pop(0) + let at = f.code.rel([0x85, 0xC0, 0x0F, 0x84]) // test eax,eax ; jz else + f.open(2, a, false) + f.frames[f.frames.length() - 1].else_patch = at + } else { + f.open(if op == 0x03 { 1 } else { 0 }, a, false) + } + } + 0x05 => { + let fr = f.frames[f.frames.length() - 1] + fr.ends.push(f.code.rel([0xE9])) + if fr.else_patch >= 0 { + f.code.patch_here(fr.else_patch) + fr.else_patch = -1 + } + f.height = fr.base + } + 0x0B => { + let fr = f.frames.pop().unwrap() + if fr.else_patch >= 0 { + f.code.patch_here(fr.else_patch) + } + for e in fr.ends { + f.code.patch_here(e) + } + f.height = fr.base + fr.arity + if f.frames.length() == 0 { + if ft.nresults == 1 { + f.code.b(0x58) + } + f.code.bs([0xC9, 0xC3]) + finished = true + } + } + 0x0C => { + f.emit_br(r.u32(), f.height) + f.dead = true + } + 0x0D => { + let depth = r.u32() + f.pop(0) + let at = f.code.rel([0x85, 0xC0, 0x0F, 0x84]) // test eax,eax ; jz skip + f.emit_br(depth, f.height) + f.code.patch_here(at) + } + 0x0F => { + f.emit_br(f.frames.length() - 1, f.height) + f.dead = true + } + 0x10 => { + let callee = r.u32() + if callee >= func_types.length() { + raise CompileError("call to unknown function \{callee}") + } + let cft = all_types[func_types[callee]] + let at = f.code.rel([0xE8]) + f.calls.push((at, callee)) + f.add_rsp(cft.nparams) + f.height -= cft.nparams + if cft.nresults == 1 { + f.push_rax() + } + } + 0x1A => { + f.code.bs([0x48, 0x83, 0xC4, 0x08]) + f.height -= 1 + } + 0x1B => { + f.pop(2) + f.pop(1) + f.pop(0) + f.code.bs([0x85, 0xD2, 0x48, 0x0F, 0x44, 0xC1]) // test edx,edx ; cmovz rax,rcx + f.push_rax() + } + 0x20 => { + let d = f.local_disp(r.u32()) + f.code.bs([0x48, 0x8B, 0x85]) + f.code.i32(d) + f.push_rax() + } + 0x21 | 0x22 => { + let d = f.local_disp(r.u32()) + f.pop(0) + if op == 0x22 { + f.push_rax() + } + f.code.bs([0x48, 0x89, 0x85]) + f.code.i32(d) + } + 0x41 => { + f.code.b(0x68) + f.code.i32(r.s32()) + f.height += 1 + } + 0x45 => { + f.pop(0) + f.code.bs([0x85, 0xC0, 0x0F, 0x94, 0xC0, 0x0F, 0xB6, 0xC0]) + f.push_rax() + } + 0x46 => f.cmp(0x94) + 0x47 => f.cmp(0x95) + 0x48 => f.cmp(0x9C) + 0x49 => f.cmp(0x92) + 0x4A => f.cmp(0x9F) + 0x4B => f.cmp(0x97) + 0x4C => f.cmp(0x9E) + 0x4D => f.cmp(0x96) + 0x4E => f.cmp(0x9D) + 0x4F => f.cmp(0x93) + 0x6A => f.binop([0x01, 0xC8]) + 0x6B => f.binop([0x29, 0xC8]) + 0x6C => f.binop([0x0F, 0xAF, 0xC1]) + 0x6D | 0x6E | 0x6F | 0x70 => f.divrem(op) + 0x71 => f.binop([0x21, 0xC8]) + 0x72 => f.binop([0x09, 0xC8]) + 0x73 => f.binop([0x31, 0xC8]) + 0x74 => f.binop([0xD3, 0xE0]) + 0x75 => f.binop([0xD3, 0xF8]) + 0x76 => f.binop([0xD3, 0xE8]) + 0x77 => f.binop([0xD3, 0xC0]) + 0x78 => f.binop([0xD3, 0xC8]) + _ => raise CompileError("unsupported opcode 0x\{op.to_string(radix=16)}") + } + } + f +} diff --git a/examples/divzero.wat b/examples/divzero.wat new file mode 100644 index 0000000..76fcc35 --- /dev/null +++ b/examples/divzero.wat @@ -0,0 +1,3 @@ +(module + (func (export "main") (result i32) + (i32.div_s (i32.const 7) (i32.sub (i32.const 3) (i32.const 3))))) diff --git a/examples/fact.wat b/examples/fact.wat new file mode 100644 index 0000000..2e08c87 --- /dev/null +++ b/examples/fact.wat @@ -0,0 +1,8 @@ +;; recursive factorial(5) = 120, plus if/else with result +(module + (func $fact (param $n i32) (result i32) + (if (result i32) (i32.le_s (local.get $n) (i32.const 1)) + (then (i32.const 1)) + (else (i32.mul (local.get $n) (call $fact (i32.sub (local.get $n) (i32.const 1))))))) + (func (export "main") (result i32) + (call $fact (i32.const 5)))) diff --git a/examples/misc.wat b/examples/misc.wat new file mode 100644 index 0000000..4720f28 --- /dev/null +++ b/examples/misc.wat @@ -0,0 +1,16 @@ +;; select, tee, rem_s, shifts, early return, nested blocks with results: -> 42 +(module + (func $pick (param $a i32) (param $b i32) (param $c i32) (result i32) + (select (local.get $a) (local.get $b) (local.get $c))) + (func (export "main") (result i32) + (local $x i32) + (local.set $x (i32.rem_s (i32.const -7) (i32.const 3))) ;; -1 + (if (i32.ne (local.get $x) (i32.const -1)) (then (return (i32.const 1)))) + (if (i32.ne (i32.shr_u (i32.const -1) (i32.const 28)) (i32.const 15)) (then (return (i32.const 2)))) + (if (i32.ne (call $pick (i32.const 10) (i32.const 20) (i32.const 0)) (i32.const 20)) (then (return (i32.const 3)))) + (if (i32.ne (call $pick (i32.const 10) (i32.const 20) (i32.const 1)) (i32.const 10)) (then (return (i32.const 4)))) + (i32.add + (block (result i32) + (drop (i32.const 99)) + (br 0 (i32.const 40))) + (local.tee $x (i32.const 2))))) diff --git a/examples/shine_rise.wat b/examples/shine_rise.wat new file mode 100644 index 0000000..ccead23 --- /dev/null +++ b/examples/shine_rise.wat @@ -0,0 +1,15 @@ +(module + (func $rise (result i32) + i32.const 6) + (func $shine (param $hour i32) (result i32) + local.get $hour + i32.const 9 + i32.lt_u + if (result i32) + unreachable + else + i32.const 1 + end) + (func (export "morning") (result i32) + call $rise + call $shine)) diff --git a/examples/sum.wat b/examples/sum.wat new file mode 100644 index 0000000..6ec495d --- /dev/null +++ b/examples/sum.wat @@ -0,0 +1,12 @@ +;; sum 1..10 with a loop -> exit code 55 +(module + (func (export "main") (result i32) + (local $i i32) (local $acc i32) + (local.set $i (i32.const 1)) + (block $done + (loop $top + (br_if $done (i32.gt_s (local.get $i) (i32.const 10))) + (local.set $acc (i32.add (local.get $acc) (local.get $i))) + (local.set $i (i32.add (local.get $i) (i32.const 1))) + (br $top))) + local.get $acc)) diff --git a/module.mbt b/module.mbt new file mode 100644 index 0000000..8700bc3 --- /dev/null +++ b/module.mbt @@ -0,0 +1,228 @@ +///| +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.. Reader { + { data, pos } +} + +///| +fn Reader::byte(self : Reader) -> Int raise CompileError { + if self.pos >= self.data.length() { + raise CompileError("unexpected end of input") + } + let b = self.data[self.pos].to_int() + self.pos += 1 + b +} + +///| +fn Reader::u32(self : Reader) -> Int raise CompileError { + let mut result = 0 + let mut shift = 0 + while true { + let b = self.byte() + result = result | ((b & 0x7F) << shift) + if (b & 0x80) == 0 { + break + } + shift += 7 + if shift > 35 { + raise CompileError("LEB128 too long") + } + } + result +} + +///| +fn Reader::s32(self : Reader) -> Int raise CompileError { + let mut result = 0 + let mut shift = 0 + let mut b = 0 + while true { + b = self.byte() + result = result | ((b & 0x7F) << shift) + shift += 7 + if (b & 0x80) == 0 { + break + } + if shift > 35 { + raise CompileError("LEB128 too long") + } + } + if shift < 32 && (b & 0x40) != 0 { + result = result | (-1 << shift) + } + result +} + +///| +fn Reader::name(self : Reader) -> String raise CompileError { + let len = self.u32() + let sb = StringBuilder() + for _ in 0../dev/null || continue + ./out/$n; echo "$n -> exit $?" +done