diff --git a/.gitattributes b/.gitattributes index 9772dd3..85d0ecf 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1,4 +1,4 @@ -*.wave linguist-language=Wave +*.wave text eol=lf linguist-language=Wave *.ps1 linguist-vendored *.sh linguist-vendored Makefile linguist-vendored diff --git a/.github/workflows/asmobj.yml b/.github/workflows/asmobj.yml new file mode 100644 index 0000000..86bc421 --- /dev/null +++ b/.github/workflows/asmobj.yml @@ -0,0 +1,105 @@ +name: Build complete Wave asmobj module + +on: + workflow_call: + inputs: + source: + description: Exact Whale source to build; defaults to the caller commit + type: string + required: false + default: '' + outputs: + artifact_name: + description: Exact archive artifact published by this prerequisite job + value: ${{ jobs.archives.outputs.artifact_name }} + +permissions: + contents: read + +jobs: + archives: + name: Wave asmobj archives and Linux conformance + runs-on: ubuntu-24.04 + timeout-minutes: 40 + outputs: + artifact_name: asmobj-${{ github.run_id }}-${{ github.run_attempt }} + env: + CARGO_INCREMENTAL: '0' + CARGO_BUILD_JOBS: '2' + RUSTUP_TOOLCHAIN: stable + steps: + - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5 + with: + ref: ${{ inputs.source || github.sha }} + persist-credentials: false + - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5 + with: + repository: wavefnd/Wave + ref: e0952ed65d07e14c6ed0aa64f3c9a5532dd7533b + path: .asmobj-bootstrap-source + persist-credentials: false + - uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6 + with: + python-version: '3.13' + - name: Install pinned compiler prerequisites + run: | + sudo apt-get update + sudo apt-get install --no-install-recommends -y wget software-properties-common ninja-build + wget --tries=3 --timeout=30 https://apt.llvm.org/llvm.sh -O "$RUNNER_TEMP/llvm.sh" + sudo bash "$RUNNER_TEMP/llvm.sh" 21 + sudo apt-get install --no-install-recommends -y llvm-21-dev lld-21 + printf '%s\n' \ + 'LLVM_SYS_211_PREFIX=/usr/lib/llvm-21' \ + 'LLVM_CONFIG_PATH=/usr/lib/llvm-21/bin/llvm-config' \ + 'AR=/usr/lib/llvm-21/bin/llvm-ar' >> "$GITHUB_ENV" + echo "/usr/lib/llvm-21/bin" >> "$GITHUB_PATH" + rustup toolchain install 1.89.0 --profile minimal + rustup toolchain install stable --profile minimal + - name: Build each archive from the same complete source module + run: | + for target in \ + x86_64-unknown-linux-gnu \ + aarch64-unknown-linux-gnu \ + riscv64gc-unknown-linux-gnu \ + x86_64-pc-windows-msvc \ + aarch64-pc-windows-msvc \ + x86_64-apple-darwin \ + aarch64-apple-darwin; do + python3 tools/build_asmobj.py --wave-source .asmobj-bootstrap-source \ + --bootstrap-dir "$RUNNER_TEMP/asmobj-bootstrap" --rust-toolchain 1.89.0 \ + --out-dir ".ci-asmobj/$target" --target "$target" --allow-network + done + - name: Compare native Linux O0 and O2 with the independent oracle + run: | + python3 tools/build_asmobj.py --wave-source .asmobj-bootstrap-source \ + --bootstrap-dir "$RUNNER_TEMP/asmobj-bootstrap" --rust-toolchain 1.89.0 \ + --out-dir "$RUNNER_TEMP/asmobj-o0" --opt-level 0 + cc -shared -Wl,--whole-archive "$RUNNER_TEMP/asmobj-o0/libwhale_asmobj.a" \ + -Wl,--no-whole-archive -o "$RUNNER_TEMP/asmobj-o0.so" + cc -shared -Wl,--whole-archive .ci-asmobj/x86_64-unknown-linux-gnu/libwhale_asmobj.a \ + -Wl,--no-whole-archive -o "$RUNNER_TEMP/asmobj-o2.so" + asmobj_python="$(python3 -c 'import sys; print(sys.executable)')" + for optimization in 0 2; do + timeout 120s python3 tools/fuzz_limits.py --memory-mib 512 -- \ + "$asmobj_python" tools/check_asmobj.py \ + --library "$RUNNER_TEMP/asmobj-o$optimization.so" --cases 10000 + done + - name: Build, test and install the Meson source product + run: | + python3 -m pip install --disable-pip-version-check meson==1.8.5 + cargo fetch --locked + meson setup "$RUNNER_TEMP/whale-meson" \ + -Dwave-source="$GITHUB_WORKSPACE/.asmobj-bootstrap-source" \ + -Dwave-bootstrap-dir="$RUNNER_TEMP/asmobj-bootstrap" -Dsocket-cli=true + meson compile -C "$RUNNER_TEMP/whale-meson" + meson test -C "$RUNNER_TEMP/whale-meson" --print-errorlogs + DESTDIR="$RUNNER_TEMP/whale-meson-install" meson install -C "$RUNNER_TEMP/whale-meson" + "$RUNNER_TEMP/whale-meson-install/usr/local/bin/whale" --version + - name: Retain target-specific archives and provenance + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 + with: + name: asmobj-${{ github.run_id }}-${{ github.run_attempt }} + path: .ci-asmobj/ + include-hidden-files: true + if-no-files-found: error + retention-days: 7 diff --git a/.github/workflows/coverage.yml b/.github/workflows/coverage.yml index 011ac05..e1d68eb 100644 --- a/.github/workflows/coverage.yml +++ b/.github/workflows/coverage.yml @@ -20,14 +20,26 @@ env: RUSTUP_TOOLCHAIN: stable jobs: + asmobj: + name: Build Wave asmobj prerequisites + uses: ./.github/workflows/asmobj.yml + workspace: + needs: asmobj name: Workspace coverage runs-on: ubuntu-24.04 timeout-minutes: 30 + env: + WHALE_ASMOBJ_DIR: ${{ github.workspace }}/.ci-asmobj/x86_64-unknown-linux-gnu steps: - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5 with: persist-credentials: false + - name: Download complete Wave asmobj module + uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0 + with: + name: ${{ needs.asmobj.outputs.artifact_name }} + path: .ci-asmobj - uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6 with: python-version: '3.13' diff --git a/.github/workflows/maintenance.yml b/.github/workflows/maintenance.yml index 09fa410..5566390 100644 --- a/.github/workflows/maintenance.yml +++ b/.github/workflows/maintenance.yml @@ -18,6 +18,10 @@ env: RUSTUP_TOOLCHAIN: stable jobs: + asmobj: + name: Build Wave asmobj prerequisites + uses: ./.github/workflows/asmobj.yml + dependencies: name: Dependency advisories and lockfile runs-on: ubuntu-24.04 @@ -48,15 +52,22 @@ jobs: retention-days: 7 beta: + needs: asmobj name: Rust beta compatibility runs-on: ubuntu-24.04 timeout-minutes: 25 env: + WHALE_ASMOBJ_DIR: ${{ github.workspace }}/.ci-asmobj/x86_64-unknown-linux-gnu RUSTUP_TOOLCHAIN: beta steps: - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5 with: persist-credentials: false + - name: Download complete Wave asmobj module + uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0 + with: + name: ${{ needs.asmobj.outputs.artifact_name }} + path: .ci-asmobj - uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6 with: python-version: '3.13' diff --git a/.github/workflows/quality.yml b/.github/workflows/quality.yml index 5aeb326..5301df1 100644 --- a/.github/workflows/quality.yml +++ b/.github/workflows/quality.yml @@ -20,6 +20,10 @@ env: RUSTUP_TOOLCHAIN: stable jobs: + asmobj: + name: Build Wave asmobj prerequisites + uses: ./.github/workflows/asmobj.yml + format: name: Rust formatting runs-on: ubuntu-24.04 @@ -45,6 +49,7 @@ jobs: retention-days: 7 clippy: + needs: asmobj name: Clippy / ${{ matrix.features }} runs-on: ubuntu-24.04 timeout-minutes: 20 @@ -53,11 +58,17 @@ jobs: matrix: features: [default, all] env: + WHALE_ASMOBJ_DIR: ${{ github.workspace }}/.ci-asmobj/x86_64-unknown-linux-gnu FEATURE_FLAGS: ${{ matrix.features == 'all' && '--all-features' || '' }} steps: - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5 with: persist-credentials: false + - name: Download complete Wave asmobj module + uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0 + with: + name: ${{ needs.asmobj.outputs.artifact_name }} + path: .ci-asmobj - uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6 with: python-version: '3.13' @@ -76,15 +87,22 @@ jobs: retention-days: 7 docs: + needs: asmobj name: Public crate documentation runs-on: ubuntu-24.04 timeout-minutes: 15 env: + WHALE_ASMOBJ_DIR: ${{ github.workspace }}/.ci-asmobj/x86_64-unknown-linux-gnu RUSTDOCFLAGS: -D warnings steps: - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5 with: persist-credentials: false + - name: Download complete Wave asmobj module + uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0 + with: + name: ${{ needs.asmobj.outputs.artifact_name }} + path: .ci-asmobj - uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6 with: python-version: '3.13' @@ -121,6 +139,8 @@ jobs: run: python tools/ci.py run --name actionlint -- /tmp/actionlint -color - name: Check CI helper failure handling run: python tools/ci.py run --name runner-tests -- python -m unittest discover -s tools -p test_*.py -v + - name: Check core module dependency direction + run: python tools/ci.py run --name module-layers -- python tools/check_module_layers.py - name: Retain command logs and reproduction evidence if: always() uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 @@ -132,15 +152,22 @@ jobs: retention-days: 7 bounded-validation: + needs: asmobj name: Bounded fuzz, memory model and AST schemas runs-on: ubuntu-24.04 timeout-minutes: 20 env: + WHALE_ASMOBJ_DIR: ${{ github.workspace }}/.ci-asmobj/x86_64-unknown-linux-gnu WHALE_FUZZ_ARTIFACT_DIR: .ci-artifacts/fuzz steps: - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5 with: persist-credentials: false + - name: Download complete Wave asmobj module + uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0 + with: + name: ${{ needs.asmobj.outputs.artifact_name }} + path: .ci-asmobj - uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6 with: python-version: '3.13' diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 92af82e..d9a1905 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -28,13 +28,22 @@ env: CARGO_INCREMENTAL: '0' jobs: + asmobj: + name: Build Wave asmobj prerequisites + uses: ./.github/workflows/asmobj.yml + with: + source: ${{ inputs.source }} + source: + needs: asmobj name: Validate release source runs-on: ubuntu-24.04 timeout-minutes: 30 outputs: source: ${{ steps.identity.outputs.source }} version: ${{ steps.identity.outputs.version }} + env: + WHALE_ASMOBJ_DIR: ${{ github.workspace }}/.ci-asmobj/x86_64-unknown-linux-gnu steps: - name: Check input syntax before checkout env: @@ -48,6 +57,11 @@ jobs: ref: ${{ inputs.source }} fetch-depth: 0 persist-credentials: false + - name: Download complete Wave asmobj module + uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0 + with: + name: ${{ needs.asmobj.outputs.artifact_name }} + path: .ci-asmobj - uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6 with: python-version: '3.13' @@ -71,7 +85,7 @@ jobs: package: name: Package ${{ matrix.host }} - needs: source + needs: [source, asmobj] runs-on: ${{ matrix.os }} timeout-minutes: 30 strategy: @@ -97,6 +111,7 @@ jobs: host: aarch64-pc-windows-msvc binary: target/release/whale.exe env: + WHALE_ASMOBJ_DIR: ${{ github.workspace }}/.ci-asmobj/${{ matrix.host }} SOURCE: ${{ needs.source.outputs.source }} VERSION: ${{ needs.source.outputs.version }} RUSTUP_TOOLCHAIN: stable-${{ matrix.host }} @@ -105,6 +120,11 @@ jobs: with: ref: ${{ needs.source.outputs.source }} persist-credentials: false + - name: Download complete Wave asmobj module + uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0 + with: + name: ${{ needs.asmobj.outputs.artifact_name }} + path: .ci-asmobj - uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6 with: python-version: '3.13' diff --git a/.github/workflows/rust.yml b/.github/workflows/rust.yml index 4b419ba..caf313f 100644 --- a/.github/workflows/rust.yml +++ b/.github/workflows/rust.yml @@ -20,7 +20,12 @@ env: RUSTUP_TOOLCHAIN: stable jobs: + asmobj: + name: Build Wave asmobj prerequisites + uses: ./.github/workflows/asmobj.yml + native: + needs: asmobj name: Native ${{ matrix.platform }} / ${{ matrix.features }} runs-on: ${{ matrix.os }} timeout-minutes: 30 @@ -55,12 +60,18 @@ jobs: host: x86_64-apple-darwin binary: target/debug/whale env: + WHALE_ASMOBJ_DIR: ${{ github.workspace }}/.ci-asmobj/${{ matrix.host }} RUSTUP_TOOLCHAIN: stable-${{ matrix.host }} FEATURE_FLAGS: ${{ matrix.features == 'all' && '--all-features' || '' }} steps: - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5 with: persist-credentials: false + - name: Download complete Wave asmobj module + uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0 + with: + name: ${{ needs.asmobj.outputs.artifact_name }} + path: .ci-asmobj - uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6 with: python-version: '3.13' @@ -93,6 +104,7 @@ jobs: retention-days: 7 msrv: + needs: asmobj name: Rust 1.86 / ${{ matrix.features }} runs-on: ubuntu-24.04 timeout-minutes: 20 @@ -101,12 +113,18 @@ jobs: matrix: features: [default, all] env: + WHALE_ASMOBJ_DIR: ${{ github.workspace }}/.ci-asmobj/x86_64-unknown-linux-gnu RUSTUP_TOOLCHAIN: '1.86.0' FEATURE_FLAGS: ${{ matrix.features == 'all' && '--all-features' || '' }} steps: - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5 with: persist-credentials: false + - name: Download complete Wave asmobj module + uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0 + with: + name: ${{ needs.asmobj.outputs.artifact_name }} + path: .ci-asmobj - uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6 with: python-version: '3.13' @@ -129,13 +147,21 @@ jobs: retention-days: 7 release-tests: + needs: asmobj name: Optimized regression tests runs-on: ubuntu-24.04 timeout-minutes: 25 + env: + WHALE_ASMOBJ_DIR: ${{ github.workspace }}/.ci-asmobj/x86_64-unknown-linux-gnu steps: - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5 with: persist-credentials: false + - name: Download complete Wave asmobj module + uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0 + with: + name: ${{ needs.asmobj.outputs.artifact_name }} + path: .ci-asmobj - uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6 with: python-version: '3.13' @@ -154,15 +180,22 @@ jobs: retention-days: 7 riscv: + needs: asmobj name: RISC-V Linux host / QEMU smoke runs-on: ubuntu-24.04 timeout-minutes: 25 env: + WHALE_ASMOBJ_DIR: ${{ github.workspace }}/.ci-asmobj/riscv64gc-unknown-linux-gnu CARGO_TARGET_RISCV64GC_UNKNOWN_LINUX_GNU_LINKER: riscv64-linux-gnu-gcc steps: - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5 with: persist-credentials: false + - name: Download complete Wave asmobj module + uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0 + with: + name: ${{ needs.asmobj.outputs.artifact_name }} + path: .ci-asmobj - uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6 with: python-version: '3.13' diff --git a/.github/workflows/wave-elf.yml b/.github/workflows/wave-elf.yml deleted file mode 100644 index 910a2f7..0000000 --- a/.github/workflows/wave-elf.yml +++ /dev/null @@ -1,53 +0,0 @@ -name: Wave ELF bootstrap - -on: - pull_request: - branches: [master] - push: - branches: [master] - workflow_dispatch: - -permissions: - contents: read - -concurrency: - group: wave-elf-${{ github.workflow }}-${{ github.ref }} - cancel-in-progress: true - -jobs: - wave-elf: - name: Wave ELF / Linux x86_64 - runs-on: ubuntu-24.04 - timeout-minutes: 30 - steps: - - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5 - with: - persist-credentials: false - - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5 - with: - repository: wavefnd/Wave - ref: 8a465e30aeea4b817d925cdd0e8d08c1bb029c9a - path: .wave-bootstrap - persist-credentials: false - - name: Install bootstrap dependencies - run: | - sudo apt-get update - sudo apt-get install -y wget software-properties-common - wget --tries=3 --timeout=30 https://apt.llvm.org/llvm.sh -O "$RUNNER_TEMP/llvm.sh" - sudo bash "$RUNNER_TEMP/llvm.sh" 21 - sudo apt-get install -y lld-21 - echo "LLVM_SYS_211_PREFIX=/usr/lib/llvm-21" >> "$GITHUB_ENV" - echo "LLVM_CONFIG_PATH=/usr/lib/llvm-21/bin/llvm-config" >> "$GITHUB_ENV" - echo "/usr/lib/llvm-21/bin" >> "$GITHUB_PATH" - rustup toolchain install stable --profile minimal --component clippy - - name: Build pinned Wave compiler and records - run: python3 tools/build_wave_elf.py --wave-source .wave-bootstrap --out-dir "$RUNNER_TEMP/wave-elf" - - name: Verify Wave path and independent Rust serialization - env: - RUSTUP_TOOLCHAIN: stable - run: | - export WHALE_WAVE_ELF_DIR="$RUNNER_TEMP/wave-elf" - cargo test --workspace --all-features --locked - cargo clippy --workspace --all-targets --all-features --locked -- -D warnings - cargo build --workspace --all-features --locked - python3 tools/ci_smoke.py --binary target/debug/whale --socket enabled diff --git a/.github/workflows/wave-reverse.yml b/.github/workflows/wave-reverse.yml deleted file mode 100644 index 7185cae..0000000 --- a/.github/workflows/wave-reverse.yml +++ /dev/null @@ -1,86 +0,0 @@ -name: Wave reverse bootstrap - -on: - pull_request: - branches: [master] - push: - branches: [master] - workflow_dispatch: - -permissions: - contents: read - -concurrency: - group: wave-reverse-${{ github.workflow }}-${{ github.ref }} - cancel-in-progress: true - -jobs: - wave-reverse: - name: Wave decoder and CFG / Linux x86_64 - runs-on: ubuntu-24.04 - timeout-minutes: 35 - env: - CARGO_INCREMENTAL: 0 - CARGO_BUILD_JOBS: 2 - steps: - - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5 - with: - persist-credentials: false - - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5 - with: - repository: wavefnd/Wave - ref: e0952ed65d07e14c6ed0aa64f3c9a5532dd7533b - path: .wave-reverse-bootstrap - persist-credentials: false - - name: Install pinned compiler prerequisites - run: | - sudo apt-get update - sudo apt-get install -y wget software-properties-common - wget --tries=3 --timeout=30 https://apt.llvm.org/llvm.sh -O "$RUNNER_TEMP/llvm.sh" - sudo bash "$RUNNER_TEMP/llvm.sh" 21 - sudo apt-get install -y lld-21 - echo "LLVM_SYS_211_PREFIX=/usr/lib/llvm-21" >> "$GITHUB_ENV" - echo "LLVM_CONFIG_PATH=/usr/lib/llvm-21/bin/llvm-config" >> "$GITHUB_ENV" - echo "/usr/lib/llvm-21/bin" >> "$GITHUB_PATH" - rustup toolchain install 1.89.0 --profile minimal - rustup toolchain install stable --profile minimal --component clippy - - name: Test archive publication and fingerprint rejection - run: python3 -m unittest discover -s tools -p test_build_wave_reverse.py -v - - name: Build official pinned Wave decoder and CFG - run: | - python3 tools/build_wave_reverse.py --wave-source .wave-reverse-bootstrap \ - --out-dir "$RUNNER_TEMP/wave-reverse" --rust-toolchain 1.89.0 --allow-network - echo "WHALE_WAVE_REVERSE_DIR=$RUNNER_TEMP/wave-reverse" >> "$GITHUB_ENV" - - name: Verify linked workspace and CLI - env: - RUSTUP_TOOLCHAIN: stable - run: | - cargo test --workspace --all-features --locked - cargo clippy --workspace --all-targets --all-features --locked -- -D warnings - cargo build --workspace --all-features --locked - - name: Probe actual Wave decoding and CFG under resource limits - env: - RUSTUP_TOOLCHAIN: stable - run: | - cargo test -p reverse --example fuzz_reverse --features wave --locked - cargo build -p reverse --example fuzz_reverse --features wave --locked - timeout 300s python3 tools/fuzz_limits.py --memory-mib 512 -- \ - target/debug/examples/fuzz_reverse --seed 6289366696573784625 --cases 10000 \ - --out-dir "$RUNNER_TEMP/reverse-fuzz" - - name: Preserve native replay inputs on failure - if: failure() - run: | - if [ -d "$RUNNER_TEMP/reverse-fuzz" ]; then - find "$RUNNER_TEMP/reverse-fuzz" -maxdepth 1 -type f -print -exec od -An -v -tx1 {} \; - fi - - name: Retain provenance and exact replay inputs - if: always() - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 - with: - name: wave-reverse-provenance-and-replays - path: | - ${{ runner.temp }}/wave-reverse/provenance.json - ${{ runner.temp }}/wave-reverse/reverse-core.meta - ${{ runner.temp }}/reverse-fuzz/ - if-no-files-found: warn - retention-days: 7 diff --git a/BUILDING.md b/BUILDING.md new file mode 100644 index 0000000..bd740e3 --- /dev/null +++ b/BUILDING.md @@ -0,0 +1,135 @@ +# Building Whale with Meson + +Meson configures the product, compiles the Wave `asmobj` module, then builds the +Rust components with Cargo. `assembler/asmobj/` is implemented entirely in Wave; +the remaining assembler, IR, object, linker and CLI implementations remain Rust. +Generated files and Cargo outputs stay in the selected build directory. + +## Build, test and install + +Install Meson 1.8 or newer, Ninja, Python 3.12 or newer, Git, Rust 1.86 or newer, +and a native linker. Building `asmobj` also requires LLVM 21 development +libraries, `ar`, and installed Rust **1.89.0** for the pinned Wave compiler. +The initial executable host for the linked module is **Linux x86_64 GNU**. +Whale's Rust MSRV and the Wave bootstrap's Rust version are separate requirements. + +Provide a Wave Git repository containing commit +`e0952ed65d07e14c6ed0aa64f3c9a5532dd7533b`. The helper reads that commit with +`git archive` and leaves the checkout untouched, including any local changes. +Run these commands from the Whale source root: + +```sh +# Fetch Rust dependencies separately when they are not cached. +cargo fetch --locked +# Adjust this prefix to the installed LLVM 21 location. +export LLVM_SYS_211_PREFIX=/usr/lib64/llvm21 +meson setup /tmp/whale-build \ + -Dwave-source=/absolute/path/to/Wave \ + -Dwave-bootstrap-dir=/tmp/whale-bootstrap \ + -Dwave-rust-toolchain=1.89 +meson compile -C /tmp/whale-build +meson test -C /tmp/whale-build --print-errorlogs +DESTDIR=/tmp/whale-install meson install -C /tmp/whale-build +/tmp/whale-install/usr/local/bin/whale --version +``` + +Use the installed alias `1.89` above only if it reports exactly Rust 1.89.0; +the option defaults to `1.89.0`. All four assembler architectures are selected +by default. `--buildtype=release` selects optimized Rust output, and +`-Dsocket-cli=true` includes experimental AST JSON lowering. + +Cargo resolution is locked and offline by default. `-Dcargo-offline=false` +permits host dependency downloads; `-Dwave-allow-network=true` separately permits +locked Wave compiler dependency downloads. Setup does not run Cargo or bootstrap +the compiler. Compilation schedules the pinned compiler and matching std, the +complete `asmobj` archive, and then the Whale executable. + +Each build directory has its own Cargo output and executable. Meson tracks Cargo +dependency files, local Rust sources and manifests, and the explicit `asmobj` +source list and artifact metadata. A compiler/std cache can be shared through +`wave-bootstrap-dir`; cache identities and hashes are validated before reuse. +Do not use the source tree's `target/` as a Meson build directory. + +## Reuse a built module + +Build the complete module directly when an existing archive is preferable: + +```sh +LLVM_SYS_211_PREFIX=/usr/lib64/llvm21 python3 tools/build_asmobj.py \ + --wave-source /absolute/path/to/Wave --out-dir /tmp/whale-asmobj \ + --bootstrap-dir /tmp/whale-bootstrap --rust-toolchain 1.89 +meson setup /tmp/whale-prebuilt -Dasmobj-dir=/tmp/whale-asmobj +meson compile -C /tmp/whale-prebuilt +meson test -C /tmp/whale-prebuilt --print-errorlogs +``` + +Meson requires either `wave-source` or `asmobj-dir`; `asmobj` is part of the +product. Explicit archive metadata is checked before linking. The helper records +the pinned compiler, std, source and archive hashes. Failed compilation or +archiving preserves the previous complete publication. Ambient environment +variables cannot select a different module for a Meson product. + +For work confined to Rust components, ordinary Cargo builds remain available: + +```sh +cargo build --workspace --locked +cargo test -p ir --all-features --locked +# Include the complete Wave module for assembly-to-object integration tests. +export WHALE_ASMOBJ_DIR=/tmp/whale-asmobj +cargo test --workspace --all-features --locked +``` + +Cargo never bootstraps or downloads Wave automatically. A build without the +module can inspect objects and use Rust IR APIs; assembly-to-object commands +return an explicit unavailable error. There is no Rust implementation of the +`asmobj` policies selected in its place. A linked executable needs no `wavec` +at runtime. + +## Select assembler outputs and host machines + +Architecture selection controls generated code independently of the machine +running Whale. For an AArch64-only product: + +```sh +meson setup /tmp/whale-aarch64 -Dasmobj-dir=/tmp/whale-asmobj \ + -Dasm-amd64=false -Dasm-riscv64=false -Dasm-loongarch64=false +meson compile -C /tmp/whale-aarch64 +``` + +Also set `-Dasm-aarch64=false` for a product without concrete assemblers. +`meson configure BUILD_DIR -DOPTION=VALUE` changes an existing selection. + +A Meson cross file and `-Dcargo-host-target=RUST_TRIPLE` describe the final +Whale executable host. The Rust target must agree with Meson's host machine. +Cross compilation additionally needs the matching Rust target, linker, and +module archive. The build helper's `--target` defaults to +`x86_64-unknown-linux-gnu`; producing an object for another target does not +establish that Whale runs on that host. COFF and Mach-O cross archives need +LLVM ar: set `AR=/absolute/path/to/llvm-ar`. The helper explicitly selects the +linker's archive format; GNU ar cannot produce these cross-format indexes. +The initial linked native host remains Linux x86_64 GNU. + +Native runtime tests run directly. Cross runtime tests require an explicit +`-Dhost-runner='["wrapper", "argument"]'`; otherwise they are omitted. +Arguments are passed without shell interpretation. Record omitted checks as +omitted, without treating them as executed native tests. + +## Add an architecture in the source tree + +Keep an architecture's registers, operands, parser, instructions and encoder in +separate files under `assembler//`. Shared helpers contain only +behavior needed by multiple architectures. IR target lowering belongs beside +its target implementation. + +A contribution normally updates these explicit points: + +1. Target identity and data layout in `target-spec/` when required. +2. Source/build lists and the architecture's Meson selection option. +3. Product composition in `src/builtins.rs` and deliberate CLI aliases. +4. Relocation translation in `assembler/asmobj/` and object format support. +5. Encoding, rejection, object and CLI tests, plus capability documentation. + +Official and contributed architectures use the same layout. Small central enum, +dispatch and build-list edits are expected. Run +`python3 tools/check_module_layers.py` to check dependency direction. See the [contribution guide](CONTRIBUTING.md#2-repository-structure-and-module-boundaries) +for source responsibilities and checks. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 5c204ec..387f0a5 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,289 +1,122 @@ # Contributing to Whale -Thank you for contributing to Whale, the Wave Foundation's low-level toolchain. -Code, regression tests, documentation, and review are all welcome. Keep each -contribution focused on one observable change. - -Read the [Code of Conduct](CODE_OF_CONDUCT.md) and use [MAINTAINERS](MAINTAINERS) -to find the contact for the component you are changing. Public pull request -descriptions and review comments should be written in English. +Keep contributions focused and include regression tests. Public PR descriptions +and review comments should be in English. Follow the +[Code of Conduct](CODE_OF_CONDUCT.md); component contacts are in [MAINTAINERS](MAINTAINERS). ## 1. Development setup -Install Git and stable Rust through rustup, including `rustfmt` and `clippy`. -Whale's minimum supported Rust version is 1.86.0, declared in -[Cargo.toml](Cargo.toml). Python is needed for the CI helper and CLI smoke tests; -CI uses Python 3.13. The tracked [Rust workflow](.github/workflows/rust.yml) -defines host, MSRV, and feature checks; the [quality workflow](.github/workflows/quality.yml) -defines formatting, lint, documentation, and workflow validation requirements. - -The normal build and regression suite use Whale's own components. An LLVM SDK, -Wave compiler installation, or external assembler is not required to follow the -core contribution workflow. Optional cross-host and coverage checks have their -own prerequisites in the [Rust workflow](.github/workflows/rust.yml) and -[coverage workflow](.github/workflows/coverage.yml). - -Fork `wavefnd/Whale` on GitHub, then replace `YOUR_USERNAME` below with your login: +Use [BUILDING.md](BUILDING.md) for Meson, the pinned Wave compiler, dependencies +and installation. Rust's MSRV is **1.86.0**; CI uses Python **3.13**. -```bash -git clone https://github.com/YOUR_USERNAME/Whale.git -cd Whale -git remote add upstream https://github.com/wavefnd/Whale.git -git fetch upstream -git switch -c fix/your-change upstream/master -``` - -For an existing checkout, inspect `git remote -v` first. `origin` should be your -fork and `upstream` should be `wavefnd/Whale`; do not add a duplicate remote or -change an unrelated remote silently. Start new work from the latest upstream -`master`, not from an old feature branch. +Rust component tests can run without Wave. The complete product and +assembly-to-object tests require the built Wave `asmobj` archive. A linked +executable does not need the Wave compiler at runtime. -## 2. Repository map +## 2. Repository structure and module boundaries -| Area | Responsibility | +| Sources | Responsibility | | --- | --- | -| [assembler/](assembler/) | Shared assembly APIs, diagnostics, symbols, and relocations | -| [assembler/amd64/](assembler/amd64/) | AMD64 parser, encoder, and tests | -| [assembler/aarch64/](assembler/aarch64/), [riscv64/](assembler/riscv64/), [loongarch64/](assembler/loongarch64/) | Independent fixed-width integer encoders | -| [assembler/asmobj/](assembler/asmobj/) | Shared assembler-to-object bridge with target/relocation checks | -| [backend-api/](backend-api/) | IR backend support checks and artifact emission | -| [toolchain/](toolchain/) | Target, assembler, and backend registration | -| [object/](object/) | Object model and ELF serialization | -| [target-spec/](target-spec/) | Supported output targets, data layouts, and object identities | -| [ir/](ir/) | Shared IR, builders, verification, and feature-gated socket lowering | -| [linker/](linker/) | Linker component; consult the current capability status before assuming a full native link path exists | -| [src/](src/) | `whale` CLI and command integration | -| [tests/](tests/) | Repository-level integration tests | -| [tools/](tools/) | CI helpers, smoke checks, and their tests | -| [README.md](README.md) | Public usage examples and current capability boundaries | -| [.github/](.github/) | Contribution templates and CI configuration | - -[README.md](README.md) distinguishes implemented and experimental capabilities. -The default build provides typed IR `verify` and `print`. The `socket-cli` feature -enables AST JSON `lower`; `--all-features` also -exercises the socket lowering tests. A host on which Whale runs is not -necessarily an architecture for which it can generate machine code. - -For a focused regression, start with the affected component: - -| Component | Source and test locations | Focused command from the repository root | -| --- | --- | --- | -| Assembler | [assembler/src/](assembler/src/) and [assembler/amd64/](assembler/amd64/) | `cargo test -p amd64 --locked` | -| New ISA integration | [tests/multi_isa.rs](tests/multi_isa.rs) | `cargo test --test multi_isa --locked` | -| Object | [object/src/](object/src/) | `cargo test -p object --locked` | -| IR | [ir/src/](ir/src/) and [ir/tests/](ir/tests/) | `cargo test -p ir --all-features --locked` | -| Linker | [linker/src/](linker/src/) | `cargo test -p linker --locked` | -| CLI | [src/](src/) and [tests/](tests/) | `cargo test -p whale --all-features --locked` | -| CI helpers | [tools/](tools/) | `python3 -m unittest discover -s tools -p 'test_*.py' -v` | - -Run the workspace checks in [Local verification](#5-local-verification) after -the focused regression; a single component check does not cover its consumers. +| `assembler//` | Rust registers, operands, parser and encoder for that ISA | +| `assembler/src/` | Shared Rust assembly types and helpers | +| `assembler/asmobj/` | Complete Wave assembly-to-object module | +| `toolchain/`, `backend-api/` | Rust composition, backend interfaces and external data calls to `asmobj` | +| `ir/`, `target-spec/` | Rust IR semantics, target identities and layouts | +| `object/`, `linker/` | Rust object formats, relocations and executable layout | +| `reverse/` | Rust image inspection; decoder and CFG currently unavailable | +| `src/`, `tests/` | CLI and integration tests | +| `tools/`, `.github/` | Build and verification helpers | + +Split source files by role. Shared modules must not import a concrete ISA. +`asmobj` contains only Wave sources; its Rust data boundary lives in +`toolchain/src/assembly_object.rs`. Object serialization belongs to `object`. +IR remains Rust. ### Adding an assembler or IR target -Put architecture-specific assembler crates under `assembler/` and -name each crate after its architecture, such as `amd64`. Implement -`assembler::extension::Assembler`; each implementation owns its parser and AST. -For an IR backend, implement `backend_api::Backend` and declare its `TargetSpec`. -Register extensions through `toolchain::Registry`; built-ins are composed in -`src/builtins.rs`. Keep target implementations out of the shared API crates. -See `examples/external-target/` for a complete registration and emission example; -run `cargo test -p external-target --locked` when changing extension contracts. - -## 3. Submit a contribution - -### Choosing a first issue - -Start with the [open good first issues](https://github.com/wavefnd/Whale/issues?q=is%3Aissue%20is%3Aopen%20label%3A%22good%20first%20issue%22). -Read the completion criteria and linked dependencies before choosing one. For -example, [unknown-command exit status](https://github.com/wavefnd/Whale/issues/16) -has a small CLI regression, while [symbol extent validation](https://github.com/wavefnd/Whale/issues/163) -depends on the section-reference and BSS size rules. A label alone does not -mean those prerequisites or design decisions are complete. Check that an issue -is still open and unassigned, and comment with the bounded change you intend -to make so other contributors can coordinate. - -### GitHub pull requests +1. Add architecture sources under `assembler//`, or the owning IR backend. +2. Update `target-spec`, explicit dispatch and `src/builtins.rs` as needed. +3. Update Meson/Cargo source selections and Wave `asmobj` relocation mappings. +4. Test emitted bytes, metadata, rejected inputs and CLI behavior. -Target `wavefnd/Whale:master` from a topic branch in your fork. Use the pull -request template to explain the change, motivation, compatibility impact, and -validation. A focused documentation contribution does not need a new issue just -to open a PR. Link an existing report or design discussion when it is relevant. +Official and contributed architectures follow the same process. Central enum, +dispatch and build-list edits are expected. Run `python3 tools/check_module_layers.py` +to check dependency direction. See [BUILDING.md](BUILDING.md#select-assembler-outputs-and-host-machines) +for product selection and executable-host versus output-target settings. -Stage only the intended files and sign off every commit: - -```bash -git add path/to/changed-file -git commit -s -m "docs: clarify the assembler contribution workflow" -git push -u origin HEAD -``` - -Replace the example path and message with your actual change. Do not combine -unrelated refactors, generated artifacts, or repository-wide formatting with a -bug fix. When responding to review, push to the same PR branch and summarize -what changed and which checks were rerun. +## 3. Submit a contribution -### Email patches +Target `wavefnd/Whale:master` from a branch in your fork. Check open issues for +existing work and dependencies; coordinate before starting a shared issue. +A documentation fix does not require a new issue. -Email patches can be sent to the component contact in [MAINTAINERS](MAINTAINERS). -Include `[Whale PATCH]` in the subject so the project is unambiguous. For a single -signed-off commit: +Describe the problem, resulting behavior, compatibility changes and checks run. +Link relevant issues; use closing references only for completed requirements. +Keep fixes on the same PR branch. Do not merge or publish a release as part of +opening a PR. -```bash -git format-patch -1 --subject-prefix="Whale PATCH" -git send-email --to=luna@lunastev.org 0001-*.patch -``` - -`git send-email` may require a separate package and mail configuration. Send only -the intended patch files, include validation results, and identify the base -commit. A series should have one logical change per patch and a cover letter. -Do not submit the same change independently by email and PR without linking the -two discussions. Whale does not currently provide Wave's maintainer-discovery -or patch-verification scripts; use the contacts and checks documented here. +Email patches may be sent to the component contact in [MAINTAINERS](MAINTAINERS) +with `[Whale PATCH]` in the subject. ## 4. Developer Certificate of Origin -Every submitted commit must include a `Signed-off-by:` trailer, added by -`git commit -s`, certifying the [Developer Certificate of Origin](https://developercertificate.org/). -Use your own contribution identity and email address: +Sign off every commit under the [Developer Certificate of Origin](https://developercertificate.org/): -```text -Signed-off-by: Your Name +```sh +git add path/to/changed-file +git commit -s -m "component: describe the change" ``` -Sign-off is not the same as a cryptographic commit signature. Preserve existing -authorship and sign-offs when revising someone else's patch; do not sign on -another person's behalf. Contributions without the required sign-off need to be -corrected before acceptance. +The `Signed-off-by` name and email must identify the contributor certifying the +change. A sign-off is separate from cryptographic commit signing. Preserve +existing authorship and attribution. ## 5. Local verification -Run these checks from the repository root with the committed `Cargo.lock`: +For assembly-to-object and CLI checks, first build `asmobj` as described in +[BUILDING.md](BUILDING.md), then supply its archive explicitly: -```bash +```sh +export WHALE_ASMOBJ_DIR=/absolute/path/to/built-asmobj python3 tools/format-rust.py --check -cargo clippy --workspace --all-targets --locked -- -D warnings -cargo clippy --workspace --all-targets --all-features --locked -- -D warnings +python3 -m unittest discover -s tools -p 'test_*.py' -v +python3 tools/check_module_layers.py cargo test --workspace --locked cargo test --workspace --all-features --locked -cargo build --workspace --locked -``` - -For CLI changes, validate both feature configurations. Build and test the -default-feature binary before replacing it with the all-features build: - -```bash -python3 -m unittest discover -s tools -p 'test_*.py' -v -cargo build --workspace --locked -python3 tools/ci_smoke.py --binary target/debug/whale --socket disabled +cargo clippy --workspace --all-targets --all-features --locked -- -D warnings +RUSTDOCFLAGS='-D warnings' cargo doc --workspace --all-features --no-deps --locked cargo build --workspace --all-features --locked python3 tools/ci_smoke.py --binary target/debug/whale --socket enabled ``` -On Windows, use `target/debug/whale.exe` and the Python command installed on your -host. Consult the [Rust workflow](.github/workflows/rust.yml) for release-mode, -MSRV, and cross-host checks, the [quality workflow](.github/workflows/quality.yml) -for warning-free rustdoc, and the [coverage workflow](.github/workflows/coverage.yml) -for coverage prerequisites. [tools/ci.py](tools/ci.py) retains command logs and -execution metadata in `.ci-artifacts/` for reproducing failures. -Those checks are not replaced by a successful `cargo check`. - -Record exact commands, results, host, and toolchain for the checks you ran. -Identify checks you could not run and explain why; never describe a skipped -check or a hand-written model as an executed project regression. For prose-only -changes, verify paths, links, examples, and the final diff, and state that scope -in the PR rather than claiming unexecuted Rust tests passed. - -### Regression tests - -Put a regression beside the affected crate and exercise its public entry point -where practical. Establish the failing case before the fix, then retain both -negative and positive coverage. In particular: - -- Assembler changes should check emitted bytes and relevant relocation metadata, - not just successful assembly. -- Object changes should check the affected sections, symbols, offsets, and format - metadata, not only a byte pattern found somewhere in the output. -- IR changes should check the structured verifier result and preserve valid - neighboring types and signatures. -- CLI changes should cover exit status, diagnostics, and output-file behavior; - keep the matching [README usage examples](README.md#usage) and command help current. +On Windows use `target/debug/whale.exe`. For Rust-only work, start with a focused +command such as `cargo test -p ir --all-features --locked` without the archive. +See the [Rust](.github/workflows/rust.yml) and [quality](.github/workflows/quality.yml) +workflows for MSRV, host, default-feature and optimized checks. -For example, when fixing unknown-command status, add a CLI regression in -`tests/` that runs `whale` with an unknown command, checks a nonzero exit status, -and checks the diagnostic. Keep a positive case for an existing supported -command. Run that named test with `cargo test -p whale --locked ` -and confirm it fails for the reported behavior before changing the dispatch -code. After the fix, rerun it and the default/all-feature workspace checks -above. Describe the observed failure and passing results in the PR. - -Keep normal tests independent of an external assembler, linker, network access, -or a contributor's personal filesystem. Use isolated fixtures where applicable. -Do not remove existing tests, loosen expected results, or weaken CI merely to +Report exact commands and results. Distinguish cross-produced objects from +executed native tests, and state skipped checks. Do not weaken tests or CI to make a patch pass. -## 6. Code style and formatting scope - -Follow the surrounding Rust style: `snake_case` functions and variables, -`PascalCase` types, `SCREAMING_SNAKE_CASE` constants, same-line opening braces -(K&R style), and no trailing whitespace. Run the check-only formatting command -first. `cargo fmt --all` writes changes throughout the workspace and can reformat -files unrelated to your patch. +## 6. Code style and regression tests -Inspect the diff after formatting. Keep unrelated formatting in a separate -change agreed with the maintainer. When a formatting failure appears to come -from unchanged code, update to the latest upstream base and compare that base -before expanding the PR. Report a remaining baseline failure with its command -and output rather than repeatedly reverting and reapplying unrelated files. +Follow neighboring code. Check formatting before applying it, and keep unrelated +formatting out of the patch. Tests belong beside the affected component; exercise +public behavior and meaningful output, not just successful construction. +CLI tests should cover status, diagnostics and preservation of existing files. +Keep [README.md](README.md) examples and command help accurate. ## 7. Updating a PR branch -First commit or deliberately stash local edits and confirm the working tree is -clean. Check that you are on your PR branch, not `master`, then: - -```bash -git status --short -git remote -v -git fetch upstream -git rebase upstream/master -``` - -If a conflict occurs, stop and reconcile the intended change with the latest -upstream code. Stage only the resolved paths and run `git rebase --continue`. -Use `git rebase --abort` to return to the pre-rebase state when you need to -restart. Do not resolve a conflict by blindly replacing whole files with older -copies or discarding upstream fixes. - -After a successful rebase, rerun the relevant checks and inspect the complete -PR diff before updating your already-published topic branch: - -```bash -git diff --stat upstream/master...HEAD -git diff --check upstream/master...HEAD -git push --force-with-lease origin HEAD -``` - -Use a normal push when you have not rewritten published history. Coordinate any -history rewrite with other people using the branch. If the lease is rejected, -inspect the remote changes instead of retrying with `--force`. Git's -[rebase](https://git-scm.com/docs/git-rebase) and -[push](https://git-scm.com/docs/git-push) documentation describe recovery and -lease behavior in more detail. - -## 8. Maintainers, licensing, and repository policies - -Use [MAINTAINERS](MAINTAINERS) for review routing and private contact details. -Keep public technical discussion on the corresponding PR. Conduct reports go -to the private contact in [CODE_OF_CONDUCT.md](CODE_OF_CONDUCT.md). +Commit or deliberately stash local changes, then rebase onto current upstream +`master`. Reconcile conflicts without discarding upstream fixes and rerun the +affected checks. Inspect `git diff --check` before pushing. -Whale is licensed under [MPL-2.0](LICENSE), except where a file explicitly states -otherwise. Preserve existing attribution and third-party notices; see -[COPYRIGHT](COPYRIGHT) and [NOTICE](NOTICE). Whale does not inherit Wave's -separate Apache-2.0 standard-library license split. +Use a normal push for new history. After rewriting an already published branch, +use `git push --force-with-lease`; inspect a rejected lease instead of forcing it. -Read [ai.txt](ai.txt) for the repository's AI-use policy and permission contact. -Using assistance does not replace human responsibility for authorship, -licensing, sign-off, review, or accurate validation reports. Do not infer a -blanket permission exception from the availability of a contribution tool. +## 8. Licensing and repository policies -Thank you for helping make Whale's toolchain and contributor experience better. +Preserve [MPL-2.0](LICENSE) notices and attribution in [COPYRIGHT](COPYRIGHT) and +[NOTICE](NOTICE). Read [ai.txt](ai.txt) for the AI-use policy. Contributors remain +responsible for authorship, licensing, sign-off, review and accurate validation. diff --git a/Cargo.lock b/Cargo.lock index c431fb5..4b0a24c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -18,14 +18,6 @@ dependencies = [ "diagnostic", ] -[[package]] -name = "asmobj" -version = "0.1.0" -dependencies = [ - "assembler", - "object", -] - [[package]] name = "assembler" version = "0.1.0" @@ -190,8 +182,6 @@ checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" name = "reverse" version = "0.1.0" dependencies = [ - "amd64", - "assembler", "object", "serde_json", ] @@ -305,6 +295,7 @@ dependencies = [ "backend-api", "diagnostic", "ir", + "object", "target-spec", ] @@ -320,7 +311,6 @@ version = "0.1.0" dependencies = [ "aarch64", "amd64", - "asmobj", "assembler", "ir", "linker", diff --git a/Cargo.toml b/Cargo.toml index e17b057..16dcad0 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -6,7 +6,6 @@ members = [ "assembler/aarch64", "assembler/riscv64", "assembler/loongarch64", - "assembler/asmobj", "backend-api", "toolchain", "examples/external-target", @@ -26,17 +25,20 @@ edition = "2021" rust-version.workspace = true [features] -default = [] +default = ["builtin-assemblers"] +builtin-assemblers = ["asm-amd64", "asm-aarch64", "asm-riscv64", "asm-loongarch64"] +asm-amd64 = ["dep:amd64"] +asm-aarch64 = ["dep:aarch64"] +asm-riscv64 = ["dep:riscv64"] +asm-loongarch64 = ["dep:loongarch64"] socket-cli = ["ir/socket"] -wave-reverse = ["reverse/wave"] [dependencies] assembler = { path = "assembler" } -amd64 = { path = "assembler/amd64" } -aarch64 = { path = "assembler/aarch64" } -riscv64 = { path = "assembler/riscv64" } -loongarch64 = { path = "assembler/loongarch64" } -asmobj = { path = "assembler/asmobj" } +amd64 = { path = "assembler/amd64", optional = true } +aarch64 = { path = "assembler/aarch64", optional = true } +riscv64 = { path = "assembler/riscv64", optional = true } +loongarch64 = { path = "assembler/loongarch64", optional = true } toolchain = { path = "toolchain" } reverse = { path = "reverse" } linker = { path = "linker" } @@ -46,3 +48,11 @@ serde_json = "1" serde = { version = "1", features = ["derive"] } same-file = "1" tempfile = "3" + +[[example]] +name = "benchmark_probe" +required-features = ["asm-amd64"] + +[[example]] +name = "fuzz_boundaries" +required-features = ["asm-amd64"] diff --git a/README.md b/README.md index 3753537..2272d9c 100644 --- a/README.md +++ b/README.md @@ -7,7 +7,9 @@ Whale brings together an intermediate representation, assembler, object-file library, and linker infrastructure. Developed within the [Wave ecosystem](https://github.com/wavefnd/Wave), its components are intended to -serve language implementations and compiler tooling as reusable Rust libraries. +serve language implementations and compiler tooling through separately owned source +modules. Most components are Rust; the complete assembly-to-object `asmobj` +module is Wave. Whale is in active, early development. APIs and IR formats are evolving; the current capabilities are listed below. @@ -25,8 +27,8 @@ current capabilities are listed below. Explicit constant declarations retain their typed initializer expressions and evaluated values, including unused local declarations. Their compile-time evaluation does not introduce runtime arithmetic instructions. -- **Reusable components:** expose the IR, assembler, object model, and linker as - separate crates. +- **Reusable components:** separate IR, assembler, assembly-to-object mapping, + object formats and linking by responsibility. These are project goals. Complete memory-safety semantics and an end-to-end native compilation pipeline are still being developed. @@ -35,11 +37,11 @@ native compilation pipeline are still being developed. | Component | Available today | Status | | --- | --- | --- | -| Assembler | AMD64 plus initial AArch64, RV64I and LoongArch64 integer subsets; sections, symbols, ELF64 and initial AMD64/AArch64 COFF and Mach-O output | Available; new ISAs are initial subsets | +| Assembler | AMD64 plus initial AArch64, RV64I and LoongArch64 integer subsets; sections, symbols, ELF64 and initial AMD64/AArch64 COFF and Mach-O output | Object emission requires the complete Wave `asmobj` module; initial linked host Linux x86_64 GNU | | IR | Typed IR construction, text parsing/printing, bounded verification, integer/control-flow, tracked stack-memory and bounded Whale-call interpretation, and scalar AST JSON lowering | Experimental | | Object library | Object model, bounded ELF64 reading and ELF64/COFF/Mach-O relocatable serialization | Available | | Object CLI | Wrap raw input bytes in an ELF64 object with a `.text` section | Limited | -| Reverse | ELF inspection plus opt-in Wave AMD64 disassembly and CFG/xrefs | Experimental | +| Reverse | Bounded ELF/raw image inspection and typed result records | Inspection available; decoder and CFG/xrefs unavailable | | Linker | Static Linux AMD64 ELF executables from objects and ordinary archives, checked relocations and explicit entry | Initial subset | The IR target selector accepts only `x86_64-whale-linux`; unknown targets fail @@ -65,9 +67,12 @@ phase/category and available source/object context alongside typed component err [COFF object output](assembler/README.md#coff-leaf-objects) supports AMD64 and AArch64 with `whale asm --arch ID --format coff source.s -o leaf.obj`. -The bridge is the `asmobj` crate under `assembler/asmobj`. Output has a checked -256 MiB default file budget, sparse BSS and explicit format-specific relocations; -Windows native CI gates cross-object calls/data references using the system linker. +Assembly-to-object mapping is implemented entirely in Wave under +`assembler/asmobj/`. Rust buffer conversion lives outside that module in +`toolchain`; the Rust `object` module serializes the result. Output has a checked +256 MiB default file budget, sparse BSS and explicit format-specific relocations. +The initial linked module host is Linux x86_64 GNU; emitting a COFF object does +not establish native Windows execution support for this module. ELF64 object output supports AMD64, AArch64, RV64I and LoongArch64 little-endian identities. The bounded reader, static linker and reverse tools retain their AMD64 @@ -84,25 +89,40 @@ subsets, source syntax, relocation types and examples. ## Getting started -You need Git and **Rust 1.86.0 or newer**, including Cargo. Stable Rust is -recommended for development. +Use Meson for the complete product build. It builds the Wave `asmobj` module +and the Rust components in dependency order. See [BUILDING.md](BUILDING.md) for +LLVM 21, the pinned Wave compiler, Rust toolchains and archive reuse. + +On the initial Linux x86_64 GNU host: ```sh git clone https://github.com/wavefnd/Whale.git cd Whale -cargo build --release --locked +cargo fetch --locked +export LLVM_SYS_211_PREFIX=/usr/lib64/llvm21 +meson setup /tmp/whale-build --buildtype=release \ + -Dwave-source=/absolute/path/to/Wave +meson compile -C /tmp/whale-build +meson test -C /tmp/whale-build --print-errorlogs +/tmp/whale-build/whale --version ``` -The executable is written to `target/release/whale`, or -`target/release/whale.exe` on Windows. The examples below use `cargo run` so that -installing Whale on your `PATH` is optional. - -Enable experimental AST JSON lowering when building with: +Rust components require **Rust 1.86.0 or newer**. Cargo remains available for +Rust development. To run the `cargo run` assembly examples below, first build +and select the complete Wave module: ```sh -cargo build --release --locked --features socket-cli +python3 tools/build_asmobj.py --wave-source /absolute/path/to/Wave \ + --out-dir /tmp/whale-asmobj +export WHALE_ASMOBJ_DIR=/tmp/whale-asmobj +cargo build --release --locked ``` +Without that module, Cargo still builds the Rust components and IR commands; +assembly-to-object commands return an explicit unavailable error. The executable +is written to `target/release/whale` on Linux. Enable experimental AST JSON +lowering with `-Dsocket-cli=true` in Meson or `--features socket-cli` in Cargo. + ## Usage ### Assemble an AMD64 object @@ -166,8 +186,7 @@ CLI stdout writes are fallible: a closed pipe does not cause a panic, and other write errors exit with status 1 and a diagnostic. Assembly, object and link reporting continues after a closed pipe, preserving completed artifacts and real command failures. Successful IR output also treats a closed pipe as success. Canonical IR and scalar results -retain their normal stdout format. `-o` still publishes atomically. The optional -Wave bootstrap likewise replaces its archive only after successful creation, +retain their normal stdout format. `-o` still publishes atomically. The Wave module build likewise replaces its archive only after successful creation, preserving the previous archive on an archiver failure. ### Execute scalar integer IR @@ -589,10 +608,10 @@ writing additionally preflights all payloads, names, synthesized symbols, string tables, metadata tables and alignment against the output budget before copying payloads or names. The default remains 256 MiB; `write_with_limit` overrides it. -[Wave control flow](ir/tests/fixtures/wave-control.wave) and -[casts](ir/tests/fixtures/wave-casts.wave) have retained format 3 outputs from -Wave's current typed HIR adapter, tested for canonical print-parse-print equality (legacy format 7 inputs, canonical format 8 output). -Text parsing does not provide IR execution or native code generation. Format 2 +IR construction, parsing, printing, verification, lowering and interpretation +remain Rust implementations. Canonical text regressions check retained IR +fixtures independently of a Wave compiler. Text parsing does not provide native +code generation. Format 2 printed text requires explicit migration; it is not silently accepted. New syntax or semantics requires an appropriate version change, with unknown versions rejected. @@ -660,35 +679,20 @@ This places the input bytes in an ELF64 `.text` section and defines a global `start` symbol at offset zero. It does not compile textual IR or disassemble existing object files. -### Optional Wave ELF record implementation - -The default Rust path needs no Wave compiler. An explicit build can use Wave for -ELF64 header, section, symbol and RELA record serialization. Layout, validation, -allocation and symbol resolution remain in Rust. This bootstrap supports a Linux -x86_64 host building a Linux x86_64 Whale binary; it does not add an output target. - -With Rust, LLVM 21 development libraries, a C linker and `ar` installed: - -```sh -git clone https://github.com/wavefnd/Wave.git /tmp/whale-wave-bootstrap -git -C /tmp/whale-wave-bootstrap checkout --detach 8a465e30aeea4b817d925cdd0e8d08c1bb029c9a -python3 tools/build_wave_elf.py --wave-source /tmp/whale-wave-bootstrap --out-dir /tmp/whale-wave-elf -WHALE_WAVE_ELF_DIR=/tmp/whale-wave-elf cargo build --locked --all-features -WHALE_WAVE_ELF_DIR=/tmp/whale-wave-elf cargo test --locked --workspace --all-features -``` +### Complete Wave assembly-to-object module -The script verifies the source revision and tracked modifications, builds the -bootstrap compiler with its lockfile, then compiles `object/wave/elf_records.wave` -with its LLVM backend. The Wave object is linked statically; the resulting Whale -needs no `wavec` at runtime. An invalid requested archive/host is a build error, -not an automatic fallback. Unset `WHALE_WAVE_ELF_DIR` to build the Rust path. -`object::formats::elf::WAVE_ELF_ENABLED` reports the selected build path. +`assembler/asmobj/` contains the complete Wave implementation of assembly-to-object +validation and mapping, split into model, section, symbol, relocation and entry +files. It replaces the former Rust `asmobj` crate. The external Rust data boundary +in `toolchain/src/assembly_object.rs` supplies buffers and converts the returned +records; object-file layout and serialization remain the separate Rust `object` +module's responsibility. -The ABI uses u64 field arrays and caller-owned output buffers with explicit -counts/capacity. No allocator ownership crosses the boundary. The Wave routine -rejects unsupported records, short buffers and field overflow before writing. -Dedicated tests compare complete ELF output with the Rust path. This is the -first partial Wave implementation, not a self-hosted Whale build. +[Meson](BUILDING.md) compiles and links this module as part of the product. +Cargo development builds select a prebuilt archive with `WHALE_ASMOBJ_DIR`. +There is one implementation of its policies: an absent module returns an explicit +unavailable error. The former partial Wave ELF-record and reverse-analysis +implementations have been removed. IR remains Rust. ### Assembly symbol metadata and library resolution @@ -849,27 +853,20 @@ Outputs publish atomically after validation and protect every input alias. Unix executables receive mode 0755 without copying setuid/setgid bits. The produced artifact targets Linux AMD64 regardless of the machine running Whale. -## Wave reverse tools +## Reverse image inspection -The reusable [reverse module](reverse/README.md) uses a Wave decoding/analysis core -with Rust file/ELF/CLI adapters. The initial linked core supports Linux AMD64 -hosts and decodes AMD64 bytes; these are separate host and decoded-ISA contracts. -Normal Cargo builds need no Wave compiler and retain ELF inspection; disassembly -reports an explicit unavailable capability until the core is built and linked. +The reusable [reverse module](reverse/README.md) provides bounded AMD64 ELF/raw +image inspection and typed result records. Inspection works in ordinary Cargo +builds: ```sh -python3 tools/build_wave_reverse.py --wave-source /path/to/Wave --out-dir /tmp/whale-wave-reverse -WHALE_WAVE_REVERSE_DIR=/tmp/whale-wave-reverse cargo build --locked --features wave-reverse -whale disasm --amd64 app.o --json -whale reverse inspect app --json +cargo run --locked -- reverse inspect app --json ``` -The explicit bootstrap uses pinned official Wave sources, matching standard -library, Rust 1.89.0 and LLVM 21. It reads committed sources without modifying the -Wave checkout; ordinary Cargo never downloads or bootstraps a compiler. See the -module guide for byte, encoding, unsupported-instruction and build contracts. -The supported decoding scope is integer/scalar-SSE AMD64 long mode, not complete -x86 coverage or recovery of original source code. +Instruction decoding and CFG/xrefs currently report an explicit unavailable +capability. The former partial Wave decoder/CFG implementation and archive +integration have been removed. Existing output files are preserved on these +failures. Image inspection does not infer source code or program reachability. Numeric cast legality, rounding and trap rules: [IR casts](ir/CASTS.md). diff --git a/assembler/README.md b/assembler/README.md index 6f598c9..80de035 100644 --- a/assembler/README.md +++ b/assembler/README.md @@ -28,10 +28,18 @@ live beside their implementations. Root integration tests cover registration, CLI behavior and the assembly-to-object boundary. `Assembler::object_target()` identifies native output. The -[`asmobj`](asmobj/) crate under this directory converts assembly metadata into -checked ELF64 objects and validates relocation namespaces against that identity. -`asmobj::to_object` builds the object model; `asmobj::write` serializes it. The CLI -composes these pieces through `toolchain::Registry` in `src/builtins.rs`. +[`asmobj`](asmobj/) module under this directory is implemented entirely in Wave. +Its model, section, symbol, relocation and entry files validate assembly metadata +and map relocation namespaces to the selected object identity. Rust-owned buffer +conversion lives outside the module in `toolchain/src/assembly_object.rs`; the +separate Rust `object` module serializes its result. The CLI composes assemblers +through `toolchain::Registry` in `src/builtins.rs`. + +Build the complete product with [Meson](../BUILDING.md). For Cargo development, +set `WHALE_ASMOBJ_DIR` to an archive built by `tools/build_asmobj.py` before the +assembly-to-object examples and integration tests below. Without the module, +these commands return an explicit unavailable error. The initial linked module +host is Linux x86_64 GNU; assembler output architectures remain independent. ```sh cargo run -- asm --aarch64 examples/isa/aarch64.s -o /tmp/aarch64.o @@ -115,9 +123,10 @@ at 8 MiB, output at 256 MiB, records at 262,144, symbols/globals at 65,536 and sections at 4,096. Alignment/reservation sizes are checked before allocation. The object writer supports the four output identities. The bounded object reader, -Whale static linker and Wave reverse core continue to accept their documented -AMD64 subset. Passing another machine to them fails explicitly; serializing an -object does not enable a native IR backend or static linker for that machine. +Whale static linker and reverse image inspection retain their documented AMD64 +subset. Instruction decoding and CFG/xrefs are currently unavailable. Serializing +another machine's object does not enable a native IR backend, decoder or static +linker for that machine. ## Verification @@ -149,9 +158,8 @@ and [LoongArch ABI](https://github.com/loongson/la-abi-specs). ## COFF leaf objects -`asmobj` is the assembler-to-object bridge under `assembler/asmobj`; its package -and Rust crate name are both `asmobj`. `asmobj::to_object` validates metadata and -`asmobj::write` serializes the selected identity. Select `ObjectTarget::coff` +The Wave `asmobj` module validates metadata and maps the selected object +identity; the Rust object writer serializes it. Select `ObjectTarget::coff` with AMD64 or AArch64, or use `whale asm --arch aarch64 --format coff source.s -o leaf.obj`. ELF remains the default for all four assemblers. @@ -171,8 +179,9 @@ The format follows the [Microsoft PE/COFF specification](https://learn.microsoft Ordinary tests inspect independent field fixtures without external tools. Optional `tools/check_object_oracle.py --binary target/debug/whale --format coff --readobj /path/to/llvm-readobj --linker /path/to/lld-link` checks generated objects with -LLVM and cross-links both CPU identities. Windows native CI runs the same -cross-object call/data fixture using MSVC and requires exit 42 on x64 and ARM64. +LLVM and cross-links both CPU identities. COFF object generation and cross-link +inspection are distinct from executing Whale's linked Wave module on Windows; +the initial linked module host remains Linux x86_64 GNU. ## Mach-O leaf objects @@ -210,7 +219,7 @@ written in-place; original object bytes are preserved on success/failure. The binary layout and numeric IDs follow the primary [LLVM Mach-O definitions](https://github.com/llvm/llvm-project/blob/llvmorg-21.1.0/llvm/include/llvm/BinaryFormat/MachO.h). Optional interoperability uses `tools/check_object_oracle.py --format macho` with -LLVM inspection/ld64.lld cross-linking. Native macOS Intel/ARM64 CI system-links a -C driver and two Whale objects, executes the cross-object call and dereferences -the relocated data pointer; both must produce 42. Normal Cargo tests use -independent field expectations and require no external assembler or linker. +LLVM inspection/ld64.lld cross-linking. The initial linked Wave module host is +Linux x86_64 GNU; cross-object inspection does not establish native macOS module +execution. Object-format tests use independent field expectations and require no +external assembler or linker. Full assembly-to-object integration links `asmobj`. diff --git a/assembler/asmobj/Cargo.toml b/assembler/asmobj/Cargo.toml deleted file mode 100644 index 9622230..0000000 --- a/assembler/asmobj/Cargo.toml +++ /dev/null @@ -1,9 +0,0 @@ -[package] -name = "asmobj" -version = "0.1.0" -edition = "2021" -rust-version.workspace = true - -[dependencies] -assembler = { path = ".." } -object = { path = "../../object" } diff --git a/assembler/asmobj/README.md b/assembler/asmobj/README.md new file mode 100644 index 0000000..3b49581 --- /dev/null +++ b/assembler/asmobj/README.md @@ -0,0 +1,31 @@ +# Assembler output to object model + +This complete module is implemented in Wave. It has no Rust crate, Rust +implementation, or language-specific `wave/` subdirectory. + +| Source | Role | +| --- | --- | +| `model.wave` | Private borrowed input/output records and resource checks | +| `sections.wave` | Section role and sparse-storage mapping | +| `symbols.wave` | Symbol mapping, name lookup and undefined-symbol creation | +| `relocations.wave` | ELF, COFF and Mach-O relocation translation by ISA | +| `entry.wave` | Validate the complete conversion before publishing output | + +Meson builds these explicit sources as one module. The calling Rust code in +`toolchain/src/assembly_object.rs` transfers data across the language boundary; +`object/` owns generic object validation and file serialization. There is no Rust +copy of asmobj's mapping rules. An executable built without this module reports +that assembly-to-object conversion is unavailable. + +New architectures extend the relocation source and its tests, together with +ordinary target/build-list edits elsewhere in Whale. The borrowed records are +private implementation details. + +The implementation preserves source order, creates each missing external symbol +once, and distinguishes control transfers from data relocations. It preflights +input, capacity and bounded name-lookup work before changing output records. +It borrows immutable input only for the duration of a call. + +See [BUILDING.md](../../BUILDING.md) for build commands. Independent native +checks are in `tools/check_asmobj.py`; public Rust-call integration tests are in +`toolchain/tests/assembly_object.rs`. diff --git a/assembler/asmobj/entry.wave b/assembler/asmobj/entry.wave new file mode 100644 index 0000000..e8441b8 --- /dev/null +++ b/assembler/asmobj/entry.wave @@ -0,0 +1,140 @@ +// SPDX-License-Identifier: MPL-2.0 +// Whole-module entry. Input and output records cannot alias, inputs remain +// immutable during the call, and only scratch/result may change on failure. +// Status: 1 target, 2 symbol section, 3 namespace, 4 namespace mismatch, +// 5 AArch64 COFF code, 6 format, 7 capacity, 8 transport, 9 bounded work. +export(c) fun whale_asmobj(target: ptr, sections: ptr, + section_count: u64, symbols: ptr, symbol_count: u64, + relocations: ptr, relocation_count: u64, + output_sections: ptr, section_capacity: u64, + output_symbols: ptr, symbol_capacity: u64, + output_relocations: ptr, relocation_capacity: u64, + scratch: ptr, scratch_words: u64, result: ptr) -> i32 { + if (result == null) { return 8; } + result.status = 0; + result.index = 0; + result.symbol_count = 0; + if (!asmobj_target_valid(target)) { result.status = 1; return 1; } + if (!asmobj_array_valid(sections as ptr, section_count, 56) + || !asmobj_array_valid(symbols as ptr, symbol_count, 64) + || !asmobj_array_valid(relocations as ptr, relocation_count, 72) + || !asmobj_array_valid(scratch as ptr, scratch_words, 8) + || symbol_count > 18446744073709551615 - relocation_count) { + result.status = 8; return 8; + } + var total: u64 = symbol_count + relocation_count; + var slots: u64 = scratch_words / 4; + if (total != 0 && (scratch_words % 4 != 0 || slots == 0 + || (slots & (slots - 1)) != 0 || total > slots / 2)) { + result.status = 7; return 7; + } + if (section_count > section_capacity || symbol_count > symbol_capacity + || relocation_count > relocation_capacity) { + result.status = 7; return 7; + } + if (!asmobj_array_valid(output_sections as ptr, section_count, 56) + || !asmobj_array_valid(output_symbols as ptr, symbol_count, 64) + || !asmobj_array_valid(output_relocations as ptr, relocation_count, 72)) { + result.status = 8; return 8; + } + var state: AsmobjState; + state.symbols = symbols; + state.symbol_count = symbol_count; + state.relocations = relocations; + state.relocation_count = relocation_count; + state.scratch = scratch; + state.slots = slots; + state.work = 67108864; + state.status = 0; + if (!asmobj_charge(&state, scratch_words)) { result.status = 9; return 9; } + var index: u64 = 0; + while (index < scratch_words) { scratch[index] = 0; index += 1; } + index = 0; + while (index < section_count) { + result.index = index; + if (!asmobj_charge(&state, 1)) { result.status = 9; return 9; } + if (!asmobj_section_valid(§ions[index])) { result.status = 8; return 8; } + index += 1; + } + index = 0; + while (index < symbol_count) { + result.index = index; + if (!asmobj_charge(&state, 1)) { result.status = 9; return 9; } + if (!asmobj_symbol_valid(&symbols[index])) { result.status = 8; return 8; } + if (symbols[index].section != 18446744073709551615 && symbols[index].section >= section_count) { + result.status = 2; return 2; + } + if (!asmobj_register_symbol(&state, index)) { + result.status = state.status as u64; return state.status; + } + index += 1; + } + var missing: u64 = 0; + index = 0; + while (index < relocation_count) { + result.index = index; + if (!asmobj_charge(&state, 1)) { result.status = 9; return 9; } + var relocation: ptr = &relocations[index]; + if (!asmobj_relocation_valid(relocation, section_count)) { result.status = 8; return 8; } + var slot: u64 = 0; + if (!asmobj_find_name(&state, relocation.name, relocation.name_len, &slot)) { + result.status = state.status as u64; return state.status; + } + var undefined: u64 = 1; + if (scratch[slot] != 0) { undefined = scratch[slot + 2]; } + var kind: u64 = 0; + var code: u64 = 0; + var status: i32 = asmobj_relocation_kind(&state, target, relocation, undefined, &kind, &code); + if (status != 0) { result.status = status as u64; return status; } + if (scratch[slot] == 0) { + // Emission will find this slot occupied and compare the complete + // name. Preflight stopped at an empty slot, so reserve that extra + // equality now as well as the hash/probes already charged above. + if (!asmobj_charge(&state, relocation.name_len)) { result.status = 9; return 9; } + scratch[slot] = 2; + scratch[slot + 1] = index; + scratch[slot + 2] = 1; + missing += 1; + } + index += 1; + } + var needed: u64 = symbol_count + missing; + if (needed > symbol_capacity) { result.status = 7; return 7; } + if (!asmobj_array_valid(output_symbols as ptr, needed, 64)) { + result.status = 8; return 8; + } + // Emission repeats only relocation lookups/mapping plus linear copies. Hash + // slots never move. Existing names already paid equality in preflight; + // first missing names paid their future equality when inserted above. + // Each emission lookup therefore costs no more than its preflight charge. + // The entire preflight is a conservative bound on all remaining work; reserve + // it before publishing any record, leaving emission infallible. + var spent: u64 = 67108864 - state.work; + if (spent > state.work) { result.status = 9; return 9; } + index = 0; + while (index < section_count) { + asmobj_emit_section(§ions[index], &output_sections[index]); + index += 1; + } + index = 0; + while (index < symbol_count) { output_symbols[index] = symbols[index]; index += 1; } + var next_symbol: u64 = symbol_count; + index = 0; + while (index < relocation_count) { + var relocation: ptr = &relocations[index]; + var slot: u64 = 0; + asmobj_find_name(&state, relocation.name, relocation.name_len, &slot); + var kind: u64 = 0; + var code: u64 = 0; + asmobj_relocation_kind(&state, target, relocation, scratch[slot + 2], &kind, &code); + asmobj_emit_relocation(relocation, kind, code, &output_relocations[index]); + if (scratch[slot] == 2 && scratch[slot + 1] == index) { + asmobj_emit_undefined(relocation, &output_symbols[next_symbol]); + next_symbol += 1; + } + index += 1; + } + result.index = 0; + result.symbol_count = needed; + return 0; +} diff --git a/assembler/asmobj/meson.build b/assembler/asmobj/meson.build new file mode 100644 index 0000000..efee8b3 --- /dev/null +++ b/assembler/asmobj/meson.build @@ -0,0 +1,37 @@ +# SPDX-License-Identifier: MPL-2.0 +asmobj_dependencies = [] +if asmobj_directory == '' + asmobj_directory = meson.current_build_dir() + module_target = cargo_host_target + if module_target == '' + target_os = {'linux': 'unknown-linux-gnu', 'darwin': 'apple-darwin', 'windows': 'pc-windows-msvc'} + if not target_os.has_key(host_machine.system()) + error('Set cargo-host-target for this executable host.') + endif + module_target = host_machine.cpu_family() + '-' + target_os[host_machine.system()] + endif + archive_name = module_target.contains('msvc') ? 'whale_asmobj.lib' : 'libwhale_asmobj.a' + arguments = ['--wave-source', wave_source, '--out-dir', '@OUTDIR@', + '--bootstrap-dir', wave_cache, '--target', module_target, + '--rust-toolchain', get_option('wave-rust-toolchain')] + if get_option('wave-allow-network') + arguments += ['--allow-network'] + endif + asmobj_module = custom_target('asmobj', + output: [archive_name, 'asmobj.meta', 'provenance.json'], + command: [python, files('../../tools/build_asmobj.py'), arguments], + depend_files: files('model.wave', 'sections.wave', 'symbols.wave', 'relocations.wave', 'entry.wave', + '../../tools/build_asmobj.py', '../../tools/wave_bootstrap.py'), + depends: wave_bootstrap, console: true) + asmobj_dependencies += [asmobj_module] +else + if not fs.is_absolute(asmobj_directory) + error('-Dasmobj-dir must be absolute.') + endif + archive_name = host_machine.system() == 'windows' ? 'whale_asmobj.lib' : 'libwhale_asmobj.a' + foreach artifact : [archive_name, 'asmobj.meta'] + if not fs.is_file(asmobj_directory / artifact) + error('Missing asmobj module artifact: ' + (asmobj_directory / artifact)) + endif + endforeach +endif diff --git a/assembler/asmobj/model.wave b/assembler/asmobj/model.wave new file mode 100644 index 0000000..a33666f --- /dev/null +++ b/assembler/asmobj/model.wave @@ -0,0 +1,84 @@ +// SPDX-License-Identifier: MPL-2.0 +// Private borrowed records between asmobj and its caller. This is not a target +// extension API: adding an ISA changes the owning source files and build list. +struct AsmobjTarget { + format: u64; + machine: u64; + address_bits: u64; + endian: u64; +} + +struct AsmobjSection { + name: ptr; + name_len: u64; + kind: u64; + alignment: u64; + data: ptr; + data_len: u64; + zero_fill: u64; +} + +struct AsmobjSymbol { + name: ptr; + name_len: u64; + kind: u64; + section: u64; + offset: u64; + size: u64; + binding: u64; + visibility: u64; +} + +struct AsmobjRelocation { + section: u64; + offset: u64; + name: ptr; + name_len: u64; + kind: u64; + namespace: ptr; + namespace_len: u64; + code: u64; + addend: i64; +} + +struct AsmobjResult { + status: u64; + index: u64; + symbol_count: u64; +} + +struct AsmobjState { + symbols: ptr; + symbol_count: u64; + relocations: ptr; + relocation_count: u64; + scratch: ptr; + slots: u64; + work: u64; + status: i32; +} + +fun asmobj_charge(state: ptr, amount: u64) -> bool { + if (amount > state.work) { + state.status = 9; + return false; + } + state.work -= amount; + return true; +} + +fun asmobj_span_valid(data: ptr, count: u64) -> bool { + return (count == 0 || data != null) && count <= 9223372036854775807 + && count <= 18446744073709551615 - (data as u64); +} + +fun asmobj_array_valid(data: ptr, count: u64, width: u64) -> bool { + return count <= 9223372036854775807 / width + && asmobj_span_valid(data, count * width); +} + +fun asmobj_target_valid(target: ptr) -> bool { + return target != null && target.format <= 2 && target.machine <= 3 + && target.address_bits == 64 && target.endian == 0 + && (target.format == 0 || target.machine <= 1); +} diff --git a/assembler/asmobj/relocations.wave b/assembler/asmobj/relocations.wave new file mode 100644 index 0000000..657fc46 --- /dev/null +++ b/assembler/asmobj/relocations.wave @@ -0,0 +1,71 @@ +// SPDX-License-Identifier: MPL-2.0 +// Namespace and format selection belongs to the assembler/object bridge. +// Generic object validation and serialization remain owned by the object module. +fun asmobj_literal_equal(state: ptr, data: ptr, count: u64, + literal: ptr, literal_len: u64) -> bool { + return asmobj_names_equal(state, data, count, literal, literal_len); +} + +fun asmobj_relocation_kind(state: ptr, target: ptr, + relocation: ptr, undefined: u64, kind: ptr, code: ptr) -> i32 { + kind[0] = relocation.kind; + code[0] = 0; + if (relocation.kind == 4) { + if (target.format == 2) { + kind[0] = 8; + code[0] = 2; + } else if (undefined == 0) { + kind[0] = 3; + } + return 0; + } + if (relocation.kind != 6) { return 0; } + var machine: u64 = 18446744073709551615; + if (asmobj_literal_equal(state, relocation.namespace, relocation.namespace_len, + "aarch64" as ptr, 7)) { + machine = 1; + } else if (asmobj_literal_equal(state, relocation.namespace, relocation.namespace_len, + "riscv64" as ptr, 7)) { + machine = 2; + } else if (asmobj_literal_equal(state, relocation.namespace, relocation.namespace_len, + "loongarch64" as ptr, 11)) { + machine = 3; + } + if (state.status != 0) { return state.status; } + if (machine == 18446744073709551615) { return 3; } + if (machine != target.machine) { return 4; } + if (target.format == 0) { + code[0] = relocation.code; + return 0; + } + if (target.format == 2 && machine == 1 && (relocation.code == 282 || relocation.code == 283)) { + kind[0] = 8; + code[0] = 2; + return 0; + } + if (target.format == 1 && machine == 1) { + kind[0] = 7; + if (relocation.code == 274) { code[0] = 5; } + else if (relocation.code == 280) { code[0] = 15; } + else if (relocation.code == 282 || relocation.code == 283) { code[0] = 3; } + else { return 5; } + return 0; + } + return 6; +} + +fun asmobj_relocation_valid(relocation: ptr, section_count: u64) -> bool { + return relocation.section < section_count && relocation.kind <= 6 + && relocation.code <= 4294967295 + && asmobj_span_valid(relocation.name, relocation.name_len) + && asmobj_span_valid(relocation.namespace, relocation.namespace_len); +} + +fun asmobj_emit_relocation(source: ptr, kind: u64, code: u64, + output: ptr) { + output[0] = deref source; + output.kind = kind; + output.namespace = null; + output.namespace_len = 0; + output.code = code; +} diff --git a/assembler/asmobj/sections.wave b/assembler/asmobj/sections.wave new file mode 100644 index 0000000..61d97a1 --- /dev/null +++ b/assembler/asmobj/sections.wave @@ -0,0 +1,18 @@ +// SPDX-License-Identifier: MPL-2.0 +// Section order is the object section map. Byte payloads remain borrowed until +// the caller reconstructs its ObjectFile; sparse BSS is never materialized. +fun asmobj_section_valid(section: ptr) -> bool { + return section.kind <= 3 && asmobj_span_valid(section.name, section.name_len) + && asmobj_span_valid(section.data, section.data_len); +} + +fun asmobj_section_kind(kind: u64) -> u64 { + if (kind == 2) { return 3; } + if (kind == 3) { return 2; } + return kind; +} + +fun asmobj_emit_section(source: ptr, output: ptr) { + output[0] = deref source; + output.kind = asmobj_section_kind(source.kind); +} diff --git a/assembler/asmobj/src/lib.rs b/assembler/asmobj/src/lib.rs deleted file mode 100644 index 08a0ed3..0000000 --- a/assembler/asmobj/src/lib.rs +++ /dev/null @@ -1,156 +0,0 @@ -// SPDX-License-Identifier: MPL-2.0 -//! Bridge from common assembler output to checked, target-identified ELF/COFF/Mach-O objects. -use assembler::AssemblerOutput; - -use std::collections::{HashMap, HashSet}; - -use object::{ - ObjectFile, ObjectRelocation, ObjectSymbol, ObjectTarget, RelocKind as ObjectRelocKind, - SectionKind, SymbolBinding, SymbolVisibility, -}; - -pub fn write(out: &AssemblerOutput, target: ObjectTarget) -> Result, String> { - to_object(out, target)?.write() -} - -pub fn to_object(out: &AssemblerOutput, target: ObjectTarget) -> Result { - target.validate().map_err(|e| e.to_string())?; - let mut obj = ObjectFile::with_target(target); - let mut section_map = Vec::with_capacity(out.sections.len()); - - for sec in &out.sections { - let kind = match sec.kind { - assembler::AsmSectionKind::Text => SectionKind::Text, - assembler::AsmSectionKind::Data => SectionKind::Data, - assembler::AsmSectionKind::ReadOnlyData => SectionKind::ReadOnlyData, - assembler::AsmSectionKind::Bss => SectionKind::Bss, - }; - let align = sec.align; - let idx = obj.add_section(&sec.name, kind, align); - obj.sections[idx].data = sec.data.clone(); - obj.sections[idx].zero_fill = sec.zero_fill; - section_map.push(idx); - } - - for sym in &out.symbols { - let section_index = sym - .section_index - .map(|idx| section_map.get(idx).copied().ok_or("symbol section index is invalid")) - .transpose()?; - - obj.symbols.push(ObjectSymbol { - kind: match sym.kind { - assembler::SymbolKind::NoType => object::SymbolKind::NoType, - assembler::SymbolKind::Function => object::SymbolKind::Function, - assembler::SymbolKind::Object => object::SymbolKind::Object, - }, - name: sym.name.clone(), - section_index, - value: sym.offset, - size: sym.size, - binding: if sym.is_global { SymbolBinding::Global } else { SymbolBinding::Local }, - visibility: match sym.visibility { - assembler::SymbolVisibility::Default => SymbolVisibility::Default, - assembler::SymbolVisibility::Hidden => SymbolVisibility::Hidden, - }, - }); - } - - let undefined: HashMap<&str, bool> = - out.symbols.iter().map(|s| (s.name.as_str(), s.section_index.is_none())).collect(); - let mut known: HashSet<&str> = out.symbols.iter().map(|s| s.name.as_str()).collect(); - for (asm_sec_idx, sec) in out.sections.iter().enumerate() { - let Some(&obj_sec_idx) = section_map.get(asm_sec_idx) else { - continue; - }; - - for reloc in &sec.relocs { - let is_undefined_symbol = undefined.get(reloc.symbol.as_str()).copied().unwrap_or(true); - - let kind = match reloc.kind { - assembler::assembler::RelocKind::TargetSpecific { ref namespace, code } => { - let machine = match namespace.as_str() { - "aarch64" => object::Machine::AArch64, - "riscv64" => object::Machine::RiscV64, - "loongarch64" => object::Machine::LoongArch64, - _ => return Err(format!("unsupported relocation namespace {namespace:?}")), - }; - if machine != target.machine { - return Err("relocation namespace does not match object target".into()); - } - match target.format { - object::ObjectFormat::ELF64 => { - ObjectRelocKind::TargetSpecific { machine, code } - }, - object::ObjectFormat::MachO64 - if machine == object::Machine::AArch64 && matches!(code, 282 | 283) => - { - ObjectRelocKind::MachSpecific { machine, code: 2 } - }, - object::ObjectFormat::COFF if machine == object::Machine::AArch64 => { - let code = match code { - 274 => 5, - 280 => 15, - 282 | 283 => 3, - _ => { - return Err( - "unsupported AArch64 COFF instruction relocation".into() - ) - }, - }; - ObjectRelocKind::CoffSpecific { machine, code } - }, - _ => { - return Err( - "assembler relocation namespace does not support this format" - .into(), - ) - }, - } - }, - assembler::assembler::RelocKind::Absolute64 => ObjectRelocKind::Absolute64, - assembler::assembler::RelocKind::Absolute32 => ObjectRelocKind::Absolute32, - assembler::assembler::RelocKind::SignedAbsolute32 => { - ObjectRelocKind::SignedAbsolute32 - }, - assembler::assembler::RelocKind::Relative32 => ObjectRelocKind::Relative32, - assembler::assembler::RelocKind::Branch32 - if target.format == object::ObjectFormat::MachO64 => - { - ObjectRelocKind::MachSpecific { machine: target.machine, code: 2 } - }, - assembler::assembler::RelocKind::Branch32 => { - if is_undefined_symbol { - ObjectRelocKind::PLT32 - } else { - ObjectRelocKind::Relative32 - } - }, - assembler::assembler::RelocKind::Relative8 => ObjectRelocKind::Relative8, - }; - - obj.relocations.push(ObjectRelocation { - section_index: obj_sec_idx, - offset: reloc.offset, - symbol: reloc.symbol.clone(), - addend: reloc.addend, - kind, - }); - - if known.insert(reloc.symbol.as_str()) { - obj.symbols.push(ObjectSymbol { - kind: object::SymbolKind::NoType, - name: reloc.symbol.clone(), - section_index: None, - value: 0, - size: 0, - binding: SymbolBinding::Global, - visibility: SymbolVisibility::Default, - }); - } - } - } - - obj.validate()?; - Ok(obj) -} diff --git a/assembler/asmobj/symbols.wave b/assembler/asmobj/symbols.wave new file mode 100644 index 0000000..03e4121 --- /dev/null +++ b/assembler/asmobj/symbols.wave @@ -0,0 +1,98 @@ +// SPDX-License-Identifier: MPL-2.0 +// Each hash slot is {source kind, source index, undefined flag, byte hash}. +// Source kind 1 borrows an input symbol, 2 the first relocation needing a symbol. +fun asmobj_name_hash(state: ptr, name: ptr, count: u64, + output: ptr) -> bool { + if (!asmobj_charge(state, count)) { return false; } + var hash: u64 = 14695981039346656037; + var index: u64 = 0; + while (index < count) { + hash = (hash ^ (name[index] as u64)) * 1099511628211; + index += 1; + } + output[0] = hash; + return true; +} + +fun asmobj_names_equal(state: ptr, left: ptr, left_len: u64, + right: ptr, right_len: u64) -> bool { + if (left_len != right_len) { return false; } + if (!asmobj_charge(state, left_len)) { return false; } + var index: u64 = 0; + while (index < left_len) { + if (left[index] != right[index]) { return false; } + index += 1; + } + return true; +} + +fun asmobj_find_name(state: ptr, name: ptr, count: u64, + output: ptr) -> bool { + var hash: u64 = 0; + if (!asmobj_name_hash(state, name, count, &hash)) { return false; } + var slot: u64 = hash & (state.slots - 1); + var probes: u64 = 0; + while (probes < state.slots) { + if (!asmobj_charge(state, 1)) { return false; } + var start: u64 = slot * 4; + var source: u64 = state.scratch[start]; + if (source == 0) { + state.scratch[start + 3] = hash; + output[0] = start; + return true; + } + if (state.scratch[start + 3] == hash) { + var other: ptr = null; + var other_len: u64 = 0; + var index: u64 = state.scratch[start + 1]; + if (source == 1 && index < state.symbol_count) { + other = state.symbols[index].name; + other_len = state.symbols[index].name_len; + } else if (source == 2 && index < state.relocation_count) { + other = state.relocations[index].name; + other_len = state.relocations[index].name_len; + } else { + state.status = 8; + return false; + } + if (asmobj_names_equal(state, name, count, other, other_len)) { + output[0] = start; + return true; + } + if (state.status != 0) { return false; } + } + slot = (slot + 1) & (state.slots - 1); + probes += 1; + } + state.status = 7; + return false; +} + +fun asmobj_symbol_valid(symbol: ptr) -> bool { + return symbol.kind <= 2 && symbol.binding <= 1 && symbol.visibility <= 1 + && asmobj_span_valid(symbol.name, symbol.name_len); +} + +fun asmobj_register_symbol(state: ptr, index: u64) -> bool { + var symbol: ptr = &state.symbols[index]; + var slot: u64 = 0; + if (!asmobj_find_name(state, symbol.name, symbol.name_len, &slot)) { return false; } + // Preserve every original symbol. Last definition controls branch relocation + // selection, as in the previous map; ObjectFile owns duplicate validation. + state.scratch[slot] = 1; + state.scratch[slot + 1] = index; + state.scratch[slot + 2] = 0; + if (symbol.section == 18446744073709551615) { state.scratch[slot + 2] = 1; } + return true; +} + +fun asmobj_emit_undefined(relocation: ptr, output: ptr) { + output.name = relocation.name; + output.name_len = relocation.name_len; + output.kind = 0; + output.section = 18446744073709551615; + output.offset = 0; + output.size = 0; + output.binding = 1; + output.visibility = 0; +} diff --git a/ir/tests/fixtures/README.md b/ir/tests/fixtures/README.md index cfe6514..6532149 100644 --- a/ir/tests/fixtures/README.md +++ b/ir/tests/fixtures/README.md @@ -5,25 +5,14 @@ function pointers, scoped and sparse IDs, repeated names and entry blocks stored out of execution order. Their corresponding builder/lowering tests specify the expected canonical output. -`wave-control.wave` and `wave-casts.wave` are complete Wave programs. -`wave-control-v3.wir` and `wave-casts-v3.wir` were produced by Wave's typed HIR -adapter from working-tree revision `13a406d0fe2802ccc234264baab113c19249c7a9`. -The frontend crates and adapter were copied into a temporary workspace, with -only that copy's Whale dependency pointed at this IR implementation. The source -Wave checkout was not changed. No LLVM backend or external assembler was used. -The control-flow case includes a loop, branches, short-circuit phi and direct -calls; the cast case includes signed extension, integer-to-float and float -truncation with memory loads/stores. - -`text_parser.rs` reads every retained output, verifies it and requires canonical -print-parse-print equality, upgrading the header to format 8. These tests do not require a Wave checkout -or claim native execution. To regenerate with a matching Wave checkout and a -Whale dependency containing this reader/printer, run from the Wave root: - -```sh -cargo run -- --whale build /path/to/wave-control.wave --emit=ir -cargo run -- --whale build /path/to/wave-casts.wave --emit=ir -``` +`wave-control-v3.wir` and `wave-casts-v3.wir` are retained historical text +IR outputs from Wave's typed HIR adapter. Only the language-independent IR +fixtures remain here; the old Wave source examples have been removed. +They exercise control flow, scoped IDs, calls and numeric conversions. + +`text_parser.rs` verifies these outputs and requires canonical print-parse-print +equality, upgrading the header to format 8. These tests run the Rust IR module +and do not require a Wave compiler. Legacy AST JSON formats 2/3/4 remain readable; canonical AST JSON is format 5. Canonical typed text IR is format 8 (the reader also accepts 3/4/5/6/7). Readers reject diff --git a/ir/tests/fixtures/wave-casts.wave b/ir/tests/fixtures/wave-casts.wave deleted file mode 100644 index 439789c..0000000 --- a/ir/tests/fixtures/wave-casts.wave +++ /dev/null @@ -1,6 +0,0 @@ -fun main() { - var x: i8 = 7; - var y: i32 = x as i32; - var z: f64 = y as f64; - var a: f32 = z as f32; -} diff --git a/ir/tests/fixtures/wave-control.wave b/ir/tests/fixtures/wave-control.wave deleted file mode 100644 index cfcbfe5..0000000 --- a/ir/tests/fixtures/wave-control.wave +++ /dev/null @@ -1,14 +0,0 @@ -fun increment(x: i32) -> i32 { - return x + 1; -} - -fun main() { - var i: i32 = 0; - while (i < 3) { - if (i == 1 || i == 2) { - i = increment(i); - } else { - i = i + 1; - } - } -} diff --git a/meson.build b/meson.build new file mode 100644 index 0000000..419a620 --- /dev/null +++ b/meson.build @@ -0,0 +1,125 @@ +# SPDX-License-Identifier: MPL-2.0 +project('Whale', version: '0.1.0', meson_version: '>=1.8.0', + default_options: ['buildtype=debug']) + +# Cargo compiles the current Rust components. Meson owns product selection, +# dependency scheduling, the resulting executable, tests and installation. +python = import('python').find_installation('python3') +cargo = find_program('cargo', native: true) +rustc = find_program('rustc', native: true) +fs = import('fs') +bridge = files('tools/meson_cargo.py') +selected_features = [] +assembler_outputs = [] +foreach arch : ['amd64', 'aarch64', 'riscv64', 'loongarch64'] + if get_option('asm-' + arch) + selected_features += ['asm-' + arch] + assembler_outputs += [arch] + endif +endforeach +if get_option('socket-cli') + selected_features += ['socket-cli'] +endif + +cargo_host_target = get_option('cargo-host-target') +if meson.is_cross_build() and cargo_host_target == '' + error('Cross builds require -Dcargo-host-target=RUST_TRIPLE for the Whale executable host. Assembler output selections do not choose its host.') +endif + +# asmobj is one complete Wave source module. Cargo only links it through the +# data transport in toolchain; there is no Rust implementation or fallback. +wave_source = get_option('wave-source') +wave_cache = get_option('wave-bootstrap-dir') +if wave_cache == '' + wave_cache = meson.project_build_root() / 'wave-bootstrap' +elif not fs.is_absolute(wave_cache) + error('-Dwave-bootstrap-dir must be absolute.') +endif +asmobj_directory = get_option('asmobj-dir') +if asmobj_directory == '' + if wave_source == '' or not fs.is_absolute(wave_source) or not fs.is_dir(wave_source) + error('Supply -Dwave-source=/absolute/Wave or -Dasmobj-dir=/absolute/built/module.') + endif + if build_machine.system() != 'linux' or build_machine.cpu_family() != 'x86_64' + error('Building the pinned Wave compiler currently requires a Linux x86_64 build machine; use a prebuilt asmobj module on other build machines.') + endif + bootstrap_arguments = ['bootstrap', '--wave-source', wave_source, '--cache-dir', wave_cache, + '--rust-toolchain', get_option('wave-rust-toolchain'), '--output', '@OUTPUT@'] + if get_option('wave-allow-network') + bootstrap_arguments += ['--allow-network'] + endif + wave_bootstrap = custom_target('wave-bootstrap', output: 'wave-bootstrap-ready.json', + command: [python, bridge, bootstrap_arguments], + depend_files: files('tools/wave_bootstrap.py', 'tools/meson_cargo.py'), console: true) +endif +subdir('assembler/asmobj') + +profile = 'dev' +if get_option('buildtype') in ['release', 'minsize'] + profile = 'release' +endif +optimization = get_option('optimization') +if optimization == 'plain' + optimization = '0' +elif optimization == 'g' + optimization = '1' +endif +debug_info = get_option('debug') ? '2' : '0' +binary_name = host_machine.system() == 'windows' ? 'whale.exe' : 'whale' +build_arguments = [ + 'build', '--cargo', cargo.full_path(), + '--rustc', rustc.full_path(), + '--source-root', meson.project_source_root(), + '--target-dir', meson.project_build_root() / 'cargo', + '--output', '@OUTPUT@', '--depfile', '@DEPFILE@', + '--profile', profile, '--opt-level', optimization, '--debug-info', debug_info, + '--jobs', get_option('cargo-jobs').to_string(), + '--host-system', host_machine.system(), + '--host-cpu-family', host_machine.cpu_family(), +] +if cargo_host_target != '' + build_arguments += ['--host-target', cargo_host_target] +endif +if get_option('cargo-offline') + build_arguments += ['--offline'] +endif +build_arguments += ['--asmobj-dir', asmobj_directory] +foreach feature : selected_features + build_arguments += ['--feature', feature] +endforeach + +whale = custom_target('whale-cli', + output: binary_name, + command: [python, bridge, build_arguments], + depend_files: files('Cargo.toml', 'Cargo.lock', 'tools/meson_cargo.py'), + depfile: 'whale-cargo.d', + depends: asmobj_dependencies, + build_by_default: true, + console: true, + install: true, + install_dir: get_option('bindir'), + install_mode: 'rwxr-xr-x', +) + +test('build-helper', python, args: files('tools/test_meson_build.py')) +if not meson.is_cross_build() or get_option('host-runner').length() > 0 + smoke_arguments = ['smoke', '--binary', whale] + foreach feature : selected_features + smoke_arguments += ['--feature', feature] + endforeach + foreach argument : get_option('host-runner') + smoke_arguments += ['--runner-arg=' + argument] + endforeach + test('cli-smoke', python, args: [bridge, smoke_arguments], timeout: 90) +else + message('Host runtime smoke is omitted for this cross build; explicitly set -Dhost-runner=[...] to run it.') +endif + +summary({ + 'Build machine': build_machine.system() + '/' + build_machine.cpu_family(), + 'Whale executable host': host_machine.system() + '/' + host_machine.cpu_family(), + 'Cargo host target': cargo_host_target == '' ? 'native Rust toolchain host' : cargo_host_target, + 'Assembler output modules': assembler_outputs, + 'Complete Wave module': 'assembler/asmobj', + 'Cargo offline': get_option('cargo-offline'), +}, section: 'Whale source modules') diff --git a/meson.options b/meson.options new file mode 100644 index 0000000..5cf86ef --- /dev/null +++ b/meson.options @@ -0,0 +1,29 @@ +# SPDX-License-Identifier: MPL-2.0 +option('asm-amd64', type: 'boolean', value: true, + description: 'Include the AMD64 assembler output module') +option('asm-aarch64', type: 'boolean', value: true, + description: 'Include the AArch64 assembler output module') +option('asm-riscv64', type: 'boolean', value: true, + description: 'Include the RV64I assembler output module') +option('asm-loongarch64', type: 'boolean', value: true, + description: 'Include the LoongArch64 assembler output module') +option('socket-cli', type: 'boolean', value: false, + description: 'Include experimental AST JSON lowering commands') +option('asmobj-dir', type: 'string', value: '', + description: 'Absolute directory of the complete prebuilt Wave asmobj module for the executable host') +option('wave-source', type: 'string', value: '', + description: 'Read-only Wave Git checkout containing the pinned bootstrap revision') +option('wave-bootstrap-dir', type: 'string', value: '', + description: 'Optional absolute compiler/std cache directory; default is private to this build') +option('wave-rust-toolchain', type: 'string', value: '1.89.0', + description: 'Installed Rust toolchain alias reporting the pinned Rust 1.89.0 compiler') +option('wave-allow-network', type: 'boolean', value: false, + description: 'Explicitly allow locked dependency downloads for the Wave bootstrap build') +option('cargo-host-target', type: 'string', value: '', + description: 'Rust target triple for the Whale executable host; required for cross builds') +option('cargo-offline', type: 'boolean', value: true, + description: 'Forbid Cargo dependency downloads during the build') +option('cargo-jobs', type: 'integer', min: 1, value: 2, + description: 'Maximum parallel Cargo compilation jobs') +option('host-runner', type: 'array', value: [], + description: 'Explicit wrapper and arguments for host runtime smoke tests, such as QEMU; never a shell command') diff --git a/object/build.rs b/object/build.rs deleted file mode 100644 index 61b379f..0000000 --- a/object/build.rs +++ /dev/null @@ -1,27 +0,0 @@ -// SPDX-License-Identifier: MPL-2.0 -use std::{env, path::PathBuf}; - -fn main() { - println!("cargo:rustc-check-cfg=cfg(whale_wave_elf)"); - println!("cargo:rerun-if-env-changed=WHALE_WAVE_ELF_DIR"); - if let Some(directory) = env::var_os("WHALE_WAVE_ELF_DIR") { - assert_eq!( - env::var("HOST").unwrap(), - "x86_64-unknown-linux-gnu", - "Wave ELF bootstrap currently requires a Linux x86_64 host" - ); - assert_eq!( - env::var("TARGET").unwrap(), - "x86_64-unknown-linux-gnu", - "Wave ELF bootstrap does not support cross-compiling Whale yet" - ); - let directory = - PathBuf::from(directory).canonicalize().expect("WHALE_WAVE_ELF_DIR must exist"); - let archive = directory.join("libwhale_wave_elf.a"); - assert!(archive.is_file(), "run tools/build_wave_elf.py to build libwhale_wave_elf.a"); - println!("cargo:rerun-if-changed={}", archive.display()); - println!("cargo:rustc-link-search=native={}", directory.display()); - println!("cargo:rustc-link-lib=static=whale_wave_elf"); - println!("cargo:rustc-cfg=whale_wave_elf"); - } -} diff --git a/object/src/formats/elf.rs b/object/src/formats/elf.rs index 9cc15f4..0d4a0d6 100644 --- a/object/src/formats/elf.rs +++ b/object/src/formats/elf.rs @@ -67,29 +67,6 @@ struct Elf64Header { impl Elf64Header { fn to_bytes(&self) -> [u8; 64] { - #[cfg(whale_wave_elf)] - if wave_selected() { - return wave_record::<64>( - 1, - &[ - u64::from_le_bytes(self.ident[..8].try_into().unwrap()), - u64::from_le_bytes(self.ident[8..].try_into().unwrap()), - self.type_ as u64, - self.machine as u64, - self.version as u64, - self.entry, - self.phoff, - self.shoff, - self.flags as u64, - self.ehsize as u64, - self.phentsize as u64, - self.phnum as u64, - self.shentsize as u64, - self.shnum as u64, - self.shstrndx as u64, - ], - ); - } let mut out = [0u8; 64]; out[0..16].copy_from_slice(&self.ident); out[16..18].copy_from_slice(&self.type_.to_le_bytes()); @@ -126,24 +103,6 @@ struct Elf64Shdr { impl Elf64Shdr { fn to_bytes(self) -> [u8; 64] { - #[cfg(whale_wave_elf)] - if wave_selected() { - return wave_record::<64>( - 2, - &[ - self.name as u64, - self.type_ as u64, - self.flags, - self.addr, - self.offset, - self.size, - self.link as u64, - self.info as u64, - self.addralign, - self.entsize, - ], - ); - } let mut out = [0u8; 64]; out[0..4].copy_from_slice(&self.name.to_le_bytes()); out[4..8].copy_from_slice(&self.type_.to_le_bytes()); @@ -172,20 +131,6 @@ struct Elf64Sym { impl Elf64Sym { fn to_bytes(self) -> [u8; 24] { - #[cfg(whale_wave_elf)] - if wave_selected() { - return wave_record::<24>( - 3, - &[ - self.name as u64, - self.info as u64, - self.other as u64, - self.shndx as u64, - self.value, - self.size, - ], - ); - } let mut out = [0u8; 24]; out[0..4].copy_from_slice(&self.name.to_le_bytes()); out[4] = self.info; @@ -207,10 +152,6 @@ struct Elf64Rela { impl Elf64Rela { fn to_bytes(self) -> [u8; 24] { - #[cfg(whale_wave_elf)] - if wave_selected() { - return wave_record::<24>(4, &[self.offset, self.info, self.addend as u64]); - } let mut out = [0u8; 24]; out[0..8].copy_from_slice(&self.offset.to_le_bytes()); out[8..16].copy_from_slice(&self.info.to_le_bytes()); @@ -921,133 +862,3 @@ mod layout_boundary_tests { assert!(align_up(1, 0).is_err()); } } - -/// Whether the explicitly requested Wave implementation was linked into this build. -pub const WAVE_ELF_ENABLED: bool = cfg!(whale_wave_elf); - -#[cfg(whale_wave_elf)] -unsafe extern "C" { - fn whale_wave_elf_record( - kind: u32, - fields: *const u64, - count: u64, - dest: *mut u8, - capacity: u64, - ) -> i32; -} - -#[cfg(all(whale_wave_elf, test))] -thread_local! { static USE_WAVE: std::cell::Cell = const { std::cell::Cell::new(true) }; } - -#[cfg(whale_wave_elf)] -fn wave_selected() -> bool { - #[cfg(test)] - { - USE_WAVE.with(|enabled| enabled.get()) - } - #[cfg(not(test))] - { - true - } -} - -#[cfg(whale_wave_elf)] -fn wave_record(kind: u32, fields: &[u64]) -> [u8; N] { - let mut result = [0; N]; - // The Wave routine checks count/width/capacity before writing. Both buffers - // are live, non-overlapping and caller-owned for the duration of this call. - let status = unsafe { - whale_wave_elf_record( - kind, - fields.as_ptr(), - fields.len() as u64, - result.as_mut_ptr(), - N as u64, - ) - }; - assert_eq!(status, 0, "internal Wave ELF record contract mismatch"); - result -} - -#[cfg(all(test, whale_wave_elf))] -mod wave_tests { - use super::*; - - use crate::RelocKind; - - #[test] - fn whole_objects_match_rust_with_bss_symbols_and_signed_relocations() { - for seed in [0u64, 1, 127, 65535, u32::MAX as u64] { - let mut object = ObjectFile::new(crate::ObjectFormat::ELF64); - let text = object.add_section(".text", SectionKind::Text, 16); - object.sections[text].data = vec![0; 8]; - let bss = object.add_section(".bss", SectionKind::Bss, 32); - object.sections[bss].zero_fill = (1 << 40) + seed; - object.symbols.push(crate::ObjectSymbol { - kind: crate::SymbolKind::NoType, - name: "end".into(), - section_index: Some(bss), - value: (1 << 40) + seed, - size: 0, - binding: SymbolBinding::Global, - visibility: SymbolVisibility::Hidden, - }); - object.relocations.push(crate::ObjectRelocation { - section_index: text, - offset: 0, - symbol: "external".into(), - kind: RelocKind::Absolute64, - addend: -(seed as i64), - }); - USE_WAVE.with(|v| v.set(true)); - let wave = object.write().unwrap(); - USE_WAVE.with(|v| v.set(false)); - let rust = object.write().unwrap(); - USE_WAVE.with(|v| v.set(true)); - assert_eq!(wave, rust); - let exact = wave.len() as u64; - for enabled in [true, false] { - USE_WAVE.with(|v| v.set(enabled)); - assert_eq!(object.write_with_limit(exact).unwrap(), wave); - assert!(object.write_with_limit(exact - 1).unwrap_err().contains("size limit")); - } - USE_WAVE.with(|v| v.set(true)); - } - } - - #[test] - fn bad_ffi_arguments_do_not_publish_partial_records() { - let mut buffer = [0xa5; 64]; - let fields = [0u64; 15]; - for (kind, count, capacity) in [(0, 15, 64), (1, 14, 64), (1, 15, 63)] { - assert_eq!( - unsafe { - whale_wave_elf_record( - kind, - fields.as_ptr(), - count, - buffer.as_mut_ptr(), - capacity, - ) - }, - 1 - ); - assert_eq!(buffer, [0xa5; 64]); - } - assert_eq!( - unsafe { whale_wave_elf_record(1, std::ptr::null(), 15, buffer.as_mut_ptr(), 64) }, - 1 - ); - assert_eq!( - unsafe { whale_wave_elf_record(1, fields.as_ptr(), 15, std::ptr::null_mut(), 64) }, - 1 - ); - let mut overflow = fields; - overflow[2] = 65536; - assert_eq!( - unsafe { whale_wave_elf_record(1, overflow.as_ptr(), 15, buffer.as_mut_ptr(), 64) }, - 2 - ); - assert_eq!(buffer, [0xa5; 64]); - } -} diff --git a/object/wave/elf_records.wave b/object/wave/elf_records.wave deleted file mode 100644 index 6676682..0000000 --- a/object/wave/elf_records.wave +++ /dev/null @@ -1,43 +0,0 @@ -// SPDX-License-Identifier: MPL-2.0 -// Fixed ELF64 little-endian records. Caller owns both buffers. -// Status: 0 success, 1 invalid kind/count/pointer/capacity, 2 field overflow. -export(c) fun whale_wave_elf_record(kind: u32, fields: ptr, count: u64, dest: ptr, capacity: u64) -> i32 { - var widths: array = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; - var expected: u64 = 0; - var size: u64 = 0; - if (kind == 1) { - widths = [8, 8, 2, 2, 4, 8, 8, 8, 4, 2, 2, 2, 2, 2, 2]; - expected = 15; - size = 64; - } else if (kind == 2) { - widths = [4, 4, 8, 8, 8, 8, 4, 4, 8, 8, 0, 0, 0, 0, 0]; - expected = 10; - size = 64; - } else if (kind == 3) { - widths = [4, 1, 1, 2, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0]; - expected = 6; - size = 24; - } else if (kind == 4) { - widths = [8, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; - expected = 3; - size = 24; - } else { return 1; } - if (fields == null || dest == null || count != expected || capacity < size) { return 1; } - var i: u64 = 0; - while (i < count) { - if (widths[i] < 8 && (fields[i] >> (widths[i] * 8)) != 0) { return 2; } - i += 1; - } - var offset: u64 = 0; - i = 0; - while (i < count) { - var j: u64 = 0; - while (j < widths[i]) { - dest[offset] = ((fields[i] >> (j * 8)) & 255) as u8; - offset += 1; - j += 1; - } - i += 1; - } - return 0; -} diff --git a/reverse/ABI.md b/reverse/ABI.md deleted file mode 100644 index d2a1101..0000000 --- a/reverse/ABI.md +++ /dev/null @@ -1,82 +0,0 @@ -# Reverse kernel ABI 1 - -Every pointer refers to live caller-owned storage for the duration of a call. -Byte lengths describe real readable memory; u64 buffers are naturally aligned. -The kernel allocates nothing and calls no OS/provider functions. It does not -retain pointers. Scalar quantities and u64 records use the host C ABI. - -`whale_wave_reverse_abi() -> u64` returns 1. - -`whale_wave_reverse_decode(abi, input, length, offset, output, capacity) -> i32` -accepts input bytes and output u64 words. Offset and length must fit the supplied -allocation; lengths above i64::MAX, null pointers, and offset > length are invalid. -Capacity must be at least 96 words. Only successful decoding commits 96 output -words. Every failure leaves the entire output unchanged, including capacity and -ABI failures. Rust checks the capability version before calling the kernel and -validates all returned ranges/identities before constructing typed results. - -Status codes: 0 success; 1 invalid argument/known encoding; 2 truncated; -3 unsupported; 4 overlong; 5 output capacity; 6 ABI mismatch. - -The 96-word result is zero-initialized, with these occupied fields: - -| Words | Meaning | -|---|---| -| 0..1 | ABI version=1, record words=96 | -| 2..6 | byte length, opcode ID, condition ID (16=none), operand count, flow ID | -| 7..9 | prefix count, opcode byte offset, opcode length | -| 10..13 | ModRM offset+1/value, SIB offset+1/value (zero offset means absent) | -| 14..16 | displacement offset+1, encoded byte width, raw bits | -| 17..19 | immediate offset+1, encoded byte width, raw bits | -| 20 | effective REX byte (zero=absent) | -| 24..38 | original prefix bytes in order | -| 40..55, 56..71, 72..87 | three operand records | - -Each operand begins with kind and logical bit width. Kind1=GPR,2=XMM: word2 -register index, word3 high-byte flag. High-byte GPR indices0..3 mean AH..BH. -Kind3=memory: word2 base (0 absent,1..16 RAX..R15,17 RIP), word3 index (0 absent, -1..16 register+1), word4 scale, word5 signed displacement bits. Kind4=immediate: -word2 raw encoded bits, word3 sign-extension flag, word6 encoded bit width (zero -for implicit one). Kind5=relative: word2 signed displacement bits, word6 encoded -bit width. XMM registers have physical width128; scalar memory width is32/64. - -Opcode IDs are the exhaustive ordered mapping in `model.rs::Opcode::from_code`. -Condition IDs0..15 follow the AMD64 condition encoding. Flow IDs0..9 are next, -direct call, indirect call, direct jump, indirect jump, conditional, loop, return, -trap and syscall. Relative flow values are encoded displacements, never resolved -symbols. Reserved words must not acquire new meanings without an ABI revision. - -## CFG extension - -`whale_wave_reverse_cfg(abi, input, length, base, seeds, seed_count, overlays, -overlay_count, options, options_count, workspace, workspace_words, output, -output_words) -> i32` uses disjoint live byte/u64 buffers. It invokes the same -Wave decoder internally; no predecoded host instruction stream supplies traversal. - -`options_count` is 6; options are max instructions I, max blocks B, max edges E, -max stops S, max work W, follow-calls (0/1). Seeds are byte offsets. Overlay rows -are four words: field offset, byte width, target kind, target value; target kinds -0=unresolved,1=absolute address,2=host symbol ID. Rows must be sorted/disjoint and -inside input. At most 1,000,000 rows/seeds are accepted by the raw ABI. - -Output reserves `T = 16 + 97I + 5B + 6E + 4S` words. Workspace reserves -`length + B + T` words: one ownership word per input byte, the leader queue and -staged output. The kernel rejects insufficient capacities before access. Hard -record ceilings are 1,000,000 instructions/blocks/stops and 4,000,000 edges; input -is at most 16 MiB. All size formulas fit u64 below these fixed ceilings. - -The 16-word header contains ABI, T, used instruction/block/edge/stop counts, work, -zero, and four section offsets (instruction,block,edge,stop), then reserved zeros. -Each instruction row is its byte offset followed by the 96-word decode record. -Block rows are start,end,first instruction index,count,zero. Edge rows are source -instruction offset,kind,target kind,target value,zero,zero. Stop rows are offset, -reason,conflicting instruction offset (overlap only),zero. Only used rows and the -header are copied on success; unused capacity is untouched. No failure publishes -any output word. Scratch contents are unspecified after a call. - -Additional status codes: 7 work limit,8 instruction limit,9 leader/block limit, -10 edge limit,11 stop limit. Edge kinds 0..11 are fallthrough,call,jump,conditional -true/false,loop true/false,indirect call,indirect jump,syscall,memory,address. -Stop reasons 1..9 are invalid,truncated,unsupported,overlong,overlap,end of range, -indirect jump,syscall,address overflow. Unresolved graph edges are successful -conservative analysis results, distinct from invalid ABI input or budget failure. diff --git a/reverse/Cargo.toml b/reverse/Cargo.toml index f4b9f72..31c2bd5 100644 --- a/reverse/Cargo.toml +++ b/reverse/Cargo.toml @@ -4,14 +4,6 @@ version = "0.1.0" edition = "2021" rust-version.workspace = true -[features] -default = [] -wave = [] - -[dev-dependencies] -assembler = { path = "../assembler" } -amd64 = { path = "../assembler/amd64" } - [dependencies] object = { path = "../object" } serde_json = "1" diff --git a/reverse/README.md b/reverse/README.md index f998b5e..8be5c20 100644 --- a/reverse/README.md +++ b/reverse/README.md @@ -1,204 +1,41 @@ -# Wave AMD64 reverse core +# Reverse image inspection -The decoder is implemented in `wave/amd64.wave`. Rust owns byte buffers and typed -results; it does not decode instructions as a fallback. Ordinary Cargo builds -have no Wave compiler/network dependency and return `DecodeError::CoreUnavailable`. -`backend_available()` and `backend_name()` expose that capability explicitly. +The `reverse` crate provides bounded ELF/raw image inspection and shared typed +instruction, control-flow and reference records. Its decoder and CFG +implementation are currently unavailable. `backend_available()` returns +`false`, `backend_name()` returns `"unavailable"`, `decode` returns +`DecodeError::CoreUnavailable`, and `analyze` returns +`CfgError::CoreUnavailable`. -Build the optional Linux x86-64 core from the official pinned Wave source tree: +The former partial Wave decoder and CFG implementation, build helper and +archive integration have been removed. No decoder archive or Cargo feature can +enable them. The complete Wave module currently built by Whale is the separate +[assembly-to-object module](../assembler/asmobj/). -```sh -LLVM_SYS_211_PREFIX=/usr/lib64/llvm21 python3 tools/build_wave_reverse.py \ - --wave-source /path/to/Wave --out-dir /tmp/whale-wave-reverse \ - --rust-toolchain 1.89.0 -WHALE_WAVE_REVERSE_DIR=/tmp/whale-wave-reverse \ - cargo test -p reverse --features wave --locked --jobs 2 -``` - -The helper reads the exact official commit -`e0952ed65d07e14c6ed0aa64f3c9a5532dd7533b` using `git archive`. It never changes the -supplied checkout or trusts its working tree or installed compiler. The temporary -source archive and matching std are used together, with `WAVE_STD_REVISION` set to -the immutable revision. Cargo is locked/offline unless `--allow-network` is -explicitly selected. LLVM 21 and Rust 1.89.0 are bootstrap prerequisites. An -installed toolchain alias can be passed if it reports the exact rustc version. -Wave objects use explicit PIC relocation so optimized jump tables link into Rust -PIE executables. Optimized objects may reference compiler-lowered `memcpy` and -`memset`; these are memory primitives supplied by the Rust host runtime, not -allocator or OS imports. Archive publication is atomic; provenance records source/compiler/archive hashes. -A root `wave-reverse` feature enables this optional capability in the CLI. - -This is an AMD64 whitelist, not a complete x86 decoder. Supported families are: - -- Integer MOV, ADD/OR/ADC/SBB/AND/SUB/XOR/CMP register/rm forms and the supported - group immediates; MOVZX/MOVSX/MOVSXD, LEA, TEST register/rm, IMUL two/three operand. -- NOT/NEG/DIV/IDIV; SHL/SHR/SAR with implicit one, CL and imm8; CWD/CDQ/CQO. -- PUSH/POP registers, PUSH immediate; near direct/indirect CALL/JMP; all 16 Jcc, - SETcc and CMOVcc conditions; LOOP; RET, NOP, SYSCALL and INT3. -- MOVSS/MOVSD register and scalar memory moves; ADDSS/ADDSD, SUBSS/SUBSD, - MULSS/MULSD and DIVSS/DIVSD. Mandatory F3/F2, XMM0..15 and REX R/X/B are retained. - Packed/vector instructions, conversions and VEX/EVEX are unsupported. - -The catalog includes every integer form emitted by the current encoder and the -selected scalar SSE forms. It also accepts the same supported r/m opcode forms -where the encoder currently exposes only registers. Unknown families, address32, -segment/LOCK prefixes, and noncanonical combinations of 66 with mandatory scalar -SSE F2/F3 are explicit `Unsupported` outcomes. Invalid known constraints such as -register-source LEA are distinct `Invalid` outcomes. An unsupported first opcode -never receives a guessed length. - -All reads stay inside both the supplied slice and the 15-byte instruction limit. -Missing bytes in a recognized form are `Truncated`; a known required field that -cannot fit inside 15 bytes is `Overlong`. Fifteen prefix bytes are overlong even -if no sixteenth input byte is available. Legacy prefixes after REX cancel the -earlier REX, and only the effective REX changes AH/CH/DH/BH to SPL/BPL/SIL/DIL. -Stack operations default to 64 bits. An effective REX.W takes precedence over -66; 66 selects 16 bits when REX.W is absent or cancelled by a later legacy prefix. SIB and -RIP-relative no-base sentinels do not turn into R13 merely because REX.B is set. - -`Instruction` retains the exact original bytes, operand/condition identities, -logical widths, encoded immediate/displacement fields and their byte offsets. -Immediate raw bits and sign extension are explicit. An encoded field width is -in bytes; an operand's `encoded_width` is in bits. RIP-relative and absolute SIB -memory operands remain distinct. `relative_target(base)` uses checked arithmetic; -relocation overlays belong to the host and must precede target interpretation. -No executable loading, source recovery, IR lifting or native Whale backend is -implied by this crate. The archive is generated through Wave's LLVM bootstrap. - -## Images and listing +## Image inspection `image::Image` borrows code bytes and distinguishes region-relative offsets, -file offsets and virtual addresses. ET_REL uses the bounded object importer and -retains symbolic RELA annotations. ET_EXEC uses checked ELF header access and -executable PT_LOAD file ranges, including files without section tables. Memory-only -BSS tails and pure-BSS segments are never copied or decoded; zero file sizes -require no file-backed range. Zero-sized NOTYPE linker boundary markers remain -non-code metadata when outside their defining section. TLS symbol metadata is -omitted because TLS offsets are not process virtual addresses. Dynamic/PIE images -are outside this subset. - -`whale reverse inspect file --json` works without the Wave archive. `whale disasm` -requires the linked Wave core, emits typed facts as JSON or a human listing, and -preserves unsupported/truncated bytes as data records. A linear listing does not -establish reachability after an unknown encoding. Executable listing starts at -its entry in that region; `--entry NAME|ADDRESS` selects a particular start. -Raw bytes require `--raw --amd64 --base ADDRESS`. Input/output/record budgets are -explicit; file output publishes atomically after complete success. - -Text rendering is canonical presentation, not a promise of identical reassembly -for every valid x86 encoding. Original bytes and exact encoding fields remain -available. Relocations suppress the placeholder numeric branch target and carry -symbol, addend, kind and field location independently. +file offsets and virtual addresses. ET_REL uses the bounded AMD64 object +importer and retains symbolic RELA annotations. ET_EXEC uses checked ELF header +access and executable PT_LOAD file ranges, including files without section +tables. BSS tails and pure-BSS segments are never materialized; a zero file size +requires no file-backed range. -The byte-identical textual roundtrip contract is limited to the canonical Whale -encoder outputs retained in `tests/roundtrip.rs`: selected MOV register/immediate, -ADD/SUB/XOR/CMP/TEST register/immediate, NOT/NEG/IMUL/shift register forms; -base/index/displacement MOV and MOVZX memory forms; selected scalar SSE register, -load/store and arithmetic forms; and NOP/RET. The real Wave decoder's mnemonic and -rendered operands are reassembled and compared with the original encoder bytes. -This contract excludes symbolic/relocated operands, relative control transfers, -RIP-relative memory, redundant prefixes and alternative x86 encodings. A human -listing's address/byte columns are presentation; only its mnemonic/operand facts -are assembly syntax. Other decoded forms retain their exact bytes and typed -fields without a textual reassembly guarantee. -## Conservative control flow and references - -`analyze(input, base, seeds, overlays, limits)` invokes the Wave on-demand CFG -kernel. Seeds and overlay field offsets are region-relative; `CfgTarget::Address` -is an absolute virtual address and `Symbol(id)` names the host's symbol registry. -Input is one explicitly scoped byte region, so external addresses remain edges -without being decoded. Calls are followed inside the region by default; set -`follow_calls=false` for caller-only traversal. A helper before the initial entry -or a branch target after an unknown byte gap is decoded when reached. - -Wave owns the FIFO worklist, byte-ownership map, instruction decoding, target -selection, late/backward block splitting, overlap detection and xrefs. Rust -validates and normalizes caller buffers and converts checked records. Instruction -records use discovery order; blocks use increasing byte offset and refer to -instruction indices. Seeds and overlays are normalized for deterministic output. -The first discovered instruction owns its bytes; conflicting starts/spans emit -explicit overlap stops rather than alternate invented instructions. - -Relocation fields are sorted/disjoint and binary searched under the shared work -budget. An exact overlay replaces the numeric target before enqueue; partial -field intersections become `Unresolved`. Unknown symbolic/indirect targets remain -explicit. RIP-relative/absolute memory and relocated immediate fields produce -xrefs. An indexed relocation denotes a referenced address component, not a known -full effective address. Memory/address xrefs never enqueue code; arbitrary raw -integer constants are not treated as references. RIP calculations include the -entire instruction, including trailing immediates. Indirect memory branches keep -both the memory reference and an unresolved control edge; pointer contents are -never guessed. - -Unknown/truncated/invalid/overlong decoding stops that path. Indirect jumps and -syscalls also stop with unresolved edges; no syscall return behavior is assumed. -Ordinary fallthrough at the region end is explicit. Other queued paths remain -analyzable. This conservative graph is not complete program reachability, source -recovery, a decompiler, or IR lifting. - -`CfgLimits` separately caps input bytes, instruction records, queued leaders and -blocks, edges, stops, shared work and caller-buffer memory. Queued leaders count -against the block limit even if they later conflict or fail decoding. Defaults -are 8 MiB input, 16,384 instructions, 8,192 blocks, 65,536 edges, 8,192 stops, -67,108,864 work units and 128 MiB combined work/output/normalization buffers. -Hard ceilings are 16 MiB input and 512 MiB owned buffers. Allocation reservation -failures return `CfgError::Allocation`. Work includes host normalization, kernel -input/ownership scans, binary searches, traversal, block formation and committed -record words; it is a deterministic accounting unit, not CPU instruction count. -Resource failure returns no partial graph. The raw ABI also leaves output intact; -its caller-owned workspace may be modified on either success or failure. - -The CLI exposes this kernel as `whale reverse cfg|xrefs file [--entry NAME|ADDRESS]` -with optional `--json`. Each invocation analyzes the full selected region from -one seed: the executable entry, raw base, or ET_REL `_start`; an ET_REL without -`_start` needs an explicit entry. Symbols in other regions remain symbolic edges. -Relocations use stable symbol identities rather than placeholder numeric targets. -Both text and JSON stream into the output byte ceiling before atomic publication. -`xrefs` omits fallthrough edges and retains symbolic, indirect and memory/address -references and explicit stops. CFG instruction capacity defaults to 16,384 and -is reduced for small regions. `--max-instructions`, `--max-work` (default -67,108,864) and `--max-workspace` (default 134,217,728 bytes) bound analysis; -`--max-output` independently bounds the rendered report. - -## Reproducible builds and bounded mutation probe - -The helper publishes `reverse-core.meta` alongside the archive and SHA256 -`provenance.json`. The plain metadata schema records ABI revision 1 and FNV-1a -64-bit fingerprints of the exact compilation bytes (`amd64.wave`, one newline, -then `cfg.wave`) and archive bytes. The std-only Cargo build script verifies all -four fields before linking, and watches both source files, metadata and archive. -A stale source, damaged archive, missing metadata or different ABI is a build -error with the rebuild command. FNV is a compatibility check, not authentication; -SHA256 provenance remains available for independent auditing. Compiler/archiver -failure preserves the complete previous publication. Each output rename is -atomic; an interrupted multi-file publication is rejected by the guard. - -`wave-reverse.yml` builds the official pinned compiler with Rust 1.89.0 and LLVM -21, explicitly permits locked dependency downloads in CI, and checks the linked -workspace and CLI. Ordinary Cargo builds neither bootstrap nor download Wave. - -The example requires the real linked decoder and CFG; an unavailable core fails: +Zero-sized NOTYPE linker boundary markers outside their defining section +remain non-code metadata. TLS symbols are omitted because their offsets are +not process virtual addresses. Dynamic/PIE images are outside this subset. ```sh -WHALE_WAVE_REVERSE_DIR=/tmp/whale-wave-reverse \ - cargo build -p reverse --features wave --example fuzz_reverse --locked -# Linux address-space ceiling plus wall-clock ceiling: -timeout 300s python3 tools/fuzz_limits.py --memory-mib 512 -- \ - target/debug/examples/fuzz_reverse --seed 6289366696573784625 --cases 10000 \ - --out-dir /tmp/reverse-fuzz -# Reproduce a property failure, panic, or last input before a native signal: -target/debug/examples/fuzz_reverse --replay /tmp/reverse-fuzz/current.bin \ - --out-dir /tmp/reverse-replay +cargo run --locked -- reverse inspect app --json +cargo run --locked -- reverse inspect raw.bin --raw --amd64 --base 0x400000 --json ``` -The fixed seed, nonempty valid fixtures and deterministic mutation stream exercise -prefixes, fields, truncations, suffix independence, overlaps, symbolic overlays, -work limits, block partitions, exact bytes and repeated-result determinism. Cases -are limited to 128 bytes and 1..100,000 mutations; CFG buffers are capped at 1 MiB -and work at 1,000,000 per analysis. The case bytes fully determine graph seeds, -base, overlays and options. `current.bin` is written before entering native code. -On a caught property failure/panic, the original input and reason are saved before -at most 256 deletion-minimization attempts, with a separate minimized file. A -native signal leaves `current.bin` for replay; the external limits stop hangs or -excessive memory without relying on the process to recover. No external assembler -or disassembler is needed by this probe; independent golden tests remain separate. +Inspection needs no Wave compiler or archive. Input, record, work and output +budgets remain explicit. Text and JSON reports stream into the output byte +ceiling, and file output publishes atomically after success. + +`whale disasm`, `whale reverse cfg` and `whale reverse xrefs` report their +unavailable capability and preserve an existing output file. The retained +record/rendering APIs describe supplied typed facts; they do not implement +instruction decoding or establish reachability. Source recovery, decompilation +and IR lifting remain outside the current scope. diff --git a/reverse/build.rs b/reverse/build.rs deleted file mode 100644 index 44eedd1..0000000 --- a/reverse/build.rs +++ /dev/null @@ -1,99 +0,0 @@ -// SPDX-License-Identifier: MPL-2.0 -use std::{ - env, fs, - io::Read, - path::{Path, PathBuf}, -}; - -const ABI_VERSION: &str = "1"; - -const FNV_OFFSET: u64 = 0xcbf29ce484222325; - -fn update(mut hash: u64, bytes: &[u8]) -> u64 { - for byte in bytes { - hash = (hash ^ u64::from(*byte)).wrapping_mul(0x100000001b3); - } - hash -} - -fn file_hash(path: &Path, mut hash: u64) -> Result { - let mut file = fs::File::open(path).map_err(|e| format!("{}: {e}", path.display()))?; - let mut buffer = [0; 16384]; - loop { - let count = file.read(&mut buffer).map_err(|e| e.to_string())?; - if count == 0 { - return Ok(hash); - } - hash = update(hash, &buffer[..count]); - } -} - -fn verify(directory: &Path, manifest: &Path) -> Result<(), String> { - let archive = directory.join("libwhale_wave_reverse.a"); - let metadata = directory.join("reverse-core.meta"); - let kernels = [manifest.join("wave/amd64.wave"), manifest.join("wave/cfg.wave")]; - for path in [&archive, &metadata, &kernels[0], &kernels[1]] { - println!("cargo:rerun-if-changed={}", path.display()); - } - let file = fs::File::open(&metadata).map_err(|e| format!("missing reverse-core.meta: {e}"))?; - let mut text = String::new(); - file.take(4097).read_to_string(&mut text).map_err(|e| e.to_string())?; - if text.len() > 4096 { - return Err("oversized reverse-core.meta".into()); - } - let mut fields = std::collections::BTreeMap::new(); - for line in text.lines() { - let (key, value) = line.split_once('=').ok_or("malformed reverse-core.meta")?; - if !["schema", "abi_version", "source_fnv64", "archive_fnv64"].contains(&key) - || fields.insert(key, value).is_some() - { - return Err("unknown or duplicate reverse-core.meta field".into()); - } - } - if fields.len() != 4 || fields.get("schema") != Some(&"1") { - return Err("unsupported reverse-core.meta schema".into()); - } - if fields.get("abi_version") != Some(&ABI_VERSION) { - return Err("Wave reverse ABI revision mismatch".into()); - } - let source = file_hash(&kernels[0], FNV_OFFSET)?; - let source = file_hash(&kernels[1], update(source, b"\n"))?; - if fields.get("source_fnv64") != Some(&format!("{source:016x}").as_str()) { - return Err("stale Wave reverse archive: kernel source fingerprint mismatch".into()); - } - let archive_hash = file_hash(&archive, FNV_OFFSET)?; - if fields.get("archive_fnv64") != Some(&format!("{archive_hash:016x}").as_str()) { - return Err("corrupt or mismatched Wave reverse archive fingerprint".into()); - } - Ok(()) -} - -fn main() { - println!("cargo:rustc-check-cfg=cfg(whale_wave_reverse)"); - println!("cargo:rerun-if-env-changed=WHALE_WAVE_REVERSE_DIR"); - if env::var_os("CARGO_FEATURE_WAVE").is_none() { - return; - } - let Some(directory) = env::var_os("WHALE_WAVE_REVERSE_DIR") else { - return; - }; - assert_eq!( - env::var("HOST").unwrap(), - "x86_64-unknown-linux-gnu", - "Wave reverse bootstrap currently requires a Linux x86_64 host" - ); - assert_eq!( - env::var("TARGET").unwrap(), - "x86_64-unknown-linux-gnu", - "Wave reverse bootstrap does not cross-link yet" - ); - let directory = - PathBuf::from(directory).canonicalize().expect("WHALE_WAVE_REVERSE_DIR must exist"); - let manifest = PathBuf::from(env::var_os("CARGO_MANIFEST_DIR").unwrap()); - if let Err(error) = verify(&directory, &manifest) { - panic!("{error}; rebuild with tools/build_wave_reverse.py before enabling Wave reverse"); - } - println!("cargo:rustc-link-search=native={}", directory.display()); - println!("cargo:rustc-link-lib=static=whale_wave_reverse"); - println!("cargo:rustc-cfg=whale_wave_reverse"); -} diff --git a/reverse/examples/fuzz_reverse.rs b/reverse/examples/fuzz_reverse.rs deleted file mode 100644 index f4d6300..0000000 --- a/reverse/examples/fuzz_reverse.rs +++ /dev/null @@ -1,395 +0,0 @@ -// SPDX-License-Identifier: MPL-2.0 -//! Bounded, deterministic native Wave decoder/CFG mutation and replay probe. -use reverse::*; - -use std::{ - env, fs, - io::{self, Read, Seek, SeekFrom, Write}, - panic::{catch_unwind, AssertUnwindSafe}, - path::{Path, PathBuf}, - time::{SystemTime, UNIX_EPOCH}, -}; - -const MAX_BYTES: usize = 128; - -const MAX_CASES: usize = 100_000; - -const FIXTURES: &[&[u8]] = &[ - &[0x90, 0xc3], - &[0x48, 0x89, 0xe5, 0x48, 0x83, 0xec, 8, 0xc3], - &[0x75, 3, 0x90, 0xeb, 1, 0x90, 0xc3], - &[0xe8, 0xfb, 0xff, 0xff, 0xff, 0xc3], - &[0x48, 0x8b, 4, 0x85, 0, 0, 0, 0, 0xc3], - &[0xf3, 0x45, 0x0f, 0x58, 0xc1, 0xc3], - &[0xf2, 0x0f, 0x10, 5, 0, 0, 0, 0, 0xc3], - &[0xff, 0xd0, 0xff, 0xe0], - &[0x40, 0xb4, 1, 0xc3], - &[0x66, 0x68, 0, 0x80, 0xc3], - &[0x66, 0x48, 0x68, 0x34, 0x12, 0xc3, 0x56, 0xc3], -]; - -fn require(ok: bool, reason: &str) -> Result<(), String> { - if ok { - Ok(()) - } else { - Err(reason.into()) - } -} - -fn instruction(input: &[u8], offset: usize) -> Result, String> { - let result = decode(input, offset); - require(result == decode(input, offset), "nondeterministic decoder")?; - let decoded = match result { - Ok(i) => i, - Err( - DecodeError::Invalid { .. } - | DecodeError::Truncated { .. } - | DecodeError::Unsupported { .. } - | DecodeError::Overlong { .. }, - ) => return Ok(None), - Err(e) => return Err(format!("unexpected decoder failure: {e}")), - }; - let length = usize::from(decoded.length); - require(decoded.offset == offset && (1..=15).contains(&length), "decoder offset/length")?; - let bytes = input.get(offset..offset + length).ok_or("decoder span outside input")?; - require(decoded.original_bytes() == bytes, "decoder changed original bytes")?; - let enc = &decoded.encoding; - require( - usize::from(enc.opcode_offset) + usize::from(enc.opcode_len) <= length - && (1..=2).contains(&enc.opcode_len), - "opcode span", - )?; - for byte in [enc.modrm, enc.sib].into_iter().flatten() { - require(bytes.get(usize::from(byte.offset)) == Some(&byte.value), "encoding byte")?; - } - for field in [enc.displacement, enc.immediate].into_iter().flatten() { - let start = usize::from(field.offset); - let width = usize::from(field.width); - require((1..=8).contains(&width), "encoding field width")?; - let raw = bytes.get(start..start + width).ok_or("encoding field outside instruction")?; - let mut padded = [0; 8]; - padded[..width].copy_from_slice(raw); - require(u64::from_le_bytes(padded) == field.bits, "encoding field raw bits")?; - } - let mut padded = input.to_vec(); - padded.extend_from_slice(&[0x90; 15]); - require(decode(&padded, offset) == Ok(decoded.clone()), "suffix changed complete instruction")?; - Ok(Some(decoded)) -} - -fn limits() -> CfgLimits { - CfgLimits { - max_input_bytes: MAX_BYTES, - max_instructions: MAX_BYTES, - max_blocks: MAX_BYTES, - max_edges: 1024, - max_stops: 256, - max_work: 1_000_000, - max_workspace_bytes: 1024 * 1024, - follow_calls: true, - } -} - -fn properties(bytes: &[u8]) -> Result<(), String> { - require(bytes.len() <= MAX_BYTES, "probe input bound")?; - for offset in 0..=bytes.len() { - instruction(bytes, offset)?; - } - if FIXTURES.contains(&bytes) { - // This check is also determined by the bytes, so replay includes the - // positive capability guards and cannot succeed on an error-only core. - require(decode(bytes, 0).is_ok(), "valid seed fixture did not decode")?; - let graph = analyze(bytes, 0x1000, &[0], &[], limits()).map_err(|e| e.to_string())?; - require(!graph.instructions.is_empty(), "valid seed fixture has empty graph")?; - } - // All graph parameters are pure functions of the saved bytes: a .bin file - // alone is sufficient to reproduce the complete decoder and CFG case. - let mut seeds = Vec::new(); - if let Some(last) = bytes.last() { - seeds.extend([0, usize::from(*last) % bytes.len()]); - } - let base = if bytes.first().is_some_and(|b| b & 4 != 0) { u64::MAX - 256 } else { 0x1000 }; - let mut overlays = Vec::new(); - if bytes.first().is_some_and(|b| b & 1 != 0) { - if let Ok(i) = decode(bytes, 0) { - if let Some(f) = i.encoding.displacement.or(i.encoding.immediate) { - overlays.push(FlowOverride { - field_offset: usize::from(f.offset), - width: f.width, - target: match bytes[0] % 3 { - 0 => CfgTarget::Unresolved, - 1 => CfgTarget::Symbol(77), - _ => CfgTarget::Address(base + (bytes.len() / 2) as u64), - }, - }); - } - } - } - let l = CfgLimits { follow_calls: bytes.first().is_none_or(|b| b & 2 == 0), ..limits() }; - let result = analyze(bytes, base, &seeds, &overlays, l); - require(result == analyze(bytes, base, &seeds, &overlays, l), "nondeterministic CFG")?; - let graph = result.map_err(|e| format!("unexpected bounded CFG failure: {e}"))?; - require(graph.base == base && graph.work <= l.max_work, "CFG base/work accounting")?; - let mut owners = vec![None; bytes.len()]; - let mut membership = vec![0; graph.instructions.len()]; - for (index, i) in graph.instructions.iter().enumerate() { - require(instruction(bytes, i.offset)? == Some(i.clone()), "CFG instruction mismatch")?; - let end = i.offset + usize::from(i.length); - for owner in owners.get_mut(i.offset..end).ok_or("CFG span")? { - require(owner.is_none(), "overlapping committed instructions")?; - *owner = Some(index); - } - } - let mut previous_end = 0; - for block in &graph.blocks { - require( - block.offset >= previous_end && block.offset < block.end, - "block order/nonempty interval", - )?; - let mut cursor = block.offset; - for index in &block.instruction_indices { - let i = graph.instructions.get(*index).ok_or("block instruction index")?; - require(i.offset == cursor, "noncontiguous block")?; - cursor += usize::from(i.length); - membership[*index] += 1; - } - require(cursor == block.end, "block end")?; - previous_end = block.end; - } - require(membership.iter().all(|count| *count == 1), "instruction block partition")?; - for edge in &graph.edges { - require(graph.instructions.iter().any(|i| i.offset == edge.from), "edge source")?; - } - for stop in &graph.stops { - if let Some(conflict) = stop.conflict { - require( - stop.kind == StopKind::Overlap - && graph.instructions.iter().any(|i| i.offset == conflict), - "overlap owner", - )?; - } - } - let tiny = CfgLimits { max_work: 0, ..l }; - require( - matches!( - analyze(bytes, base, &seeds, &overlays, tiny), - Err(CfgError::Limit { resource: CfgResource::Work, .. }) - ), - "zero work must reject atomically", - )?; - Ok(()) -} - -fn check(bytes: &[u8]) -> Result<(), String> { - catch_unwind(AssertUnwindSafe(|| properties(bytes))) - .unwrap_or_else(|_| Err("Rust panic".into())) -} - -fn next(state: &mut u64) -> u64 { - *state = state.wrapping_add(0x9e3779b97f4a7c15); - let mut x = *state; - x = (x ^ (x >> 30)).wrapping_mul(0xbf58476d1ce4e5b9); - x = (x ^ (x >> 27)).wrapping_mul(0x94d049bb133111eb); - x ^ (x >> 31) -} - -fn generated(state: &mut u64, case: usize) -> Vec { - let mut bytes = FIXTURES[next(state) as usize % FIXTURES.len()].to_vec(); - if case % 17 == 0 { - return bytes; - } - if case % 7 == 0 { - bytes = (0..next(state) as usize % (MAX_BYTES + 1)).map(|_| next(state) as u8).collect(); - } else { - for _ in 0..1 + next(state) % 8 { - let at = next(state) as usize % (bytes.len() + 1); - match next(state) % 4 { - 0 if at < bytes.len() => { - bytes.remove(at); - }, - 1 if bytes.len() < MAX_BYTES => { - bytes.insert(at, next(state) as u8); - }, - 2 if at < bytes.len() => { - bytes[at] ^= 1 << (next(state) % 8); - }, - _ if at < bytes.len() => bytes[at] = next(state) as u8, - _ => {}, - } - } - } - bytes -} - -fn preserve( - directory: &Path, - bytes: &[u8], - reason: &str, - seed: u64, - case: usize, - mut fails: impl FnMut(&[u8]) -> bool, -) -> io::Result { - let stamp = SystemTime::now().duration_since(UNIX_EPOCH).unwrap_or_default().as_nanos(); - let prefix = directory.join(format!("failure-{stamp}-{}", std::process::id())); - let original = prefix.with_extension("original.bin"); - // Never minimize or overwrite the original. A native signal also leaves - // current.bin, written before entering Wave, available for exact replay. - fs::write(&original, bytes)?; - fs::write(prefix.with_extension("txt"), format!("seed={seed}\ncase={case}\n{reason}\n"))?; - let mut minimized = bytes.to_vec(); - let mut at = 0; - for _ in 0..256 { - if at >= minimized.len() { - break; - } - let mut candidate = minimized.clone(); - candidate.remove(at); - if fails(&candidate) { - minimized = candidate; - } else { - at += 1; - } - } - fs::write(prefix.with_extension("min.bin"), minimized)?; - Ok(original) -} - -fn prepare_run( - directory: &Path, - replay: Option, -) -> Result<(Option>, fs::File), String> { - // Load replay before opening the journal: the selected replay may itself - // be current.bin in this same directory and must not be truncated first. - let replay = replay - .map(|path| -> Result, String> { - let mut bytes = Vec::new(); - fs::File::open(path) - .map_err(|e| e.to_string())? - .take((MAX_BYTES + 1) as u64) - .read_to_end(&mut bytes) - .map_err(|e| e.to_string())?; - require(bytes.len() <= MAX_BYTES, "replay exceeds 128-byte probe bound")?; - Ok(bytes) - }) - .transpose()?; - fs::create_dir_all(directory).map_err(|e| e.to_string())?; - let current = fs::File::create(directory.join("current.bin")).map_err(|e| e.to_string())?; - Ok((replay, current)) -} - -fn run() -> Result<(), String> { - let mut seed = 0x5748414c455f5231u64; - let mut cases = 10_000; - let mut replay = None; - let mut directory = PathBuf::from("target/fuzz-reverse"); - let mut args = env::args().skip(1); - while let Some(arg) = args.next() { - let value = - args.next().ok_or("expected --seed N, --cases N, --replay FILE or --out-dir DIR")?; - match arg.as_str() { - "--seed" => seed = value.parse().map_err(|_| "invalid decimal seed")?, - "--cases" => cases = value.parse().map_err(|_| "invalid case count")?, - "--replay" => replay = Some(PathBuf::from(value)), - "--out-dir" => directory = value.into(), - _ => return Err(format!("unknown option {arg}")), - } - } - require((1..=MAX_CASES).contains(&cases), "--cases must be in 1..=100000")?; - require( - backend_available(), - "actual Wave core required; enable wave and WHALE_WAVE_REVERSE_DIR", - )?; - let (replay, mut current) = prepare_run(&directory, replay)?; - let mut execute = |bytes: &[u8], case: usize| -> Result<(), String> { - current - .seek(SeekFrom::Start(0)) - .and_then(|_| current.set_len(0)) - .and_then(|_| current.write_all(bytes)) - .and_then(|_| current.flush()) - .map_err(|e| e.to_string())?; - if let Err(reason) = check(bytes) { - let original = preserve(&directory, bytes, &reason, seed, case, |candidate| { - check(candidate).is_err() - }) - .map_err(|e| e.to_string())?; - return Err(format!("{reason}; replay --replay {}", original.display())); - } - Ok(()) - }; - if let Some(bytes) = replay { - execute(&bytes, 0)?; - println!("Wave reverse replay passed ({} bytes)", bytes.len()); - } else { - // A broken/missing native backend cannot pass by accepting only errors. - for (case, bytes) in FIXTURES.iter().enumerate() { - execute(bytes, case)?; - } - let mut state = seed; - for case in 0..cases { - execute(&generated(&mut state, case), case)?; - } - println!( - "Wave reverse passed {} valid fixtures and {cases} mutations (seed {seed})", - FIXTURES.len() - ); - } - Ok(()) -} - -fn main() { - if let Err(error) = run() { - eprintln!("{error}"); - std::process::exit(1); - } -} - -#[cfg(test)] -mod tests { - use super::*; - - fn temporary() -> PathBuf { - let directory = env::temp_dir().join(format!( - "reverse-probe-test-{}-{}", - std::process::id(), - SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_nanos() - )); - fs::create_dir_all(&directory).unwrap(); - directory - } - - #[test] - fn replay_journal_is_loaded_before_it_is_truncated() { - let directory = temporary(); - let path = directory.join("current.bin"); - fs::write(&path, FIXTURES[0]).unwrap(); - let (replay, _journal) = prepare_run(&directory, Some(path.clone())).unwrap(); - assert_eq!(replay.as_deref(), Some(FIXTURES[0])); - fs::write(&path, [0; MAX_BYTES + 1]).unwrap(); - assert!(prepare_run(&directory, Some(path.clone())).is_err()); - assert_eq!(fs::read(path).unwrap().len(), MAX_BYTES + 1); - fs::remove_dir_all(directory).unwrap(); - } - - #[test] - fn original_failure_is_saved_before_bounded_minimization() { - let directory = temporary(); - let bytes = vec![0x90; 1024]; - fs::write(directory.join("current.bin"), &bytes).unwrap(); - let mut attempts = 0; - let original = preserve(&directory, &bytes, "injected failure", 1, 0, |_| { - let original = fs::read_dir(&directory) - .unwrap() - .map(|p| p.unwrap().path()) - .find(|p| p.to_string_lossy().ends_with("original.bin")) - .unwrap(); - assert_eq!(fs::read(original).unwrap(), bytes); - attempts += 1; - true - }) - .unwrap(); - assert_eq!(attempts, 256); - assert_eq!(fs::read(original).unwrap(), bytes); - assert_eq!(fs::read(directory.join("current.bin")).unwrap(), bytes); - fs::remove_dir_all(directory).unwrap(); - } -} diff --git a/reverse/src/cfg.rs b/reverse/src/cfg.rs index bee160c..8c22d07 100644 --- a/reverse/src/cfg.rs +++ b/reverse/src/cfg.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MPL-2.0 -//! The host validates/copies buffers; Wave owns decoding, reachability, overlaps, -//! relocation target selection, cross references and block formation. +//! Typed control-flow records and analysis limits. +//! Analysis currently reports an explicit unavailable capability. use crate::{DecodeError, Instruction}; use std::fmt; @@ -71,14 +71,14 @@ impl fmt::Display for CfgError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Self::CoreUnavailable => { - f.write_str("Wave CFG core unavailable; enable the linked Wave reverse core") + f.write_str("control-flow analysis is unavailable in this build") }, - Self::Invalid(reason) => write!(f, "invalid Wave CFG input/result: {reason}"), + Self::Invalid(reason) => write!(f, "invalid control-flow input/result: {reason}"), Self::Limit { resource, limit } => { - write!(f, "Wave CFG {resource:?} limit exceeded ({limit})") + write!(f, "control-flow {resource:?} limit exceeded ({limit})") }, - Self::Allocation => f.write_str("unable to allocate bounded Wave CFG buffers"), - Self::DecodeOutput(error) => write!(f, "Wave CFG decode record: {error}"), + Self::Allocation => f.write_str("unable to allocate bounded control-flow buffers"), + Self::DecodeOutput(error) => write!(f, "control-flow decode record: {error}"), } } } @@ -154,345 +154,14 @@ pub struct ControlFlowGraph { pub work: u64, } -/// Analyze one explicitly scoped byte region. Addresses outside it remain edges, -/// never guessed code. Seeds are region offsets. Symbol IDs belong to the host. -/// Overlays name encoded fields; intersections of a different width resolve to -/// Unresolved rather than reading a relocation placeholder as a branch target. +/// Report the missing control-flow capability without interpreting input bytes. +/// The typed input and result structures remain available to callers. pub fn analyze( - input: &[u8], - base: u64, - seeds: &[usize], - overlays: &[FlowOverride], - limits: CfgLimits, + _input: &[u8], + _base: u64, + _seeds: &[usize], + _overlays: &[FlowOverride], + _limits: CfgLimits, ) -> Result { - #[cfg(not(whale_wave_reverse))] - { - let _ = (input, base, seeds, overlays, limits); - Err(CfgError::CoreUnavailable) - } - #[cfg(whale_wave_reverse)] - { - native::analyze(input, base, seeds, overlays, limits) - } -} - -#[cfg(whale_wave_reverse)] -mod native { - use super::*; - - use crate::{ABI_VERSION, DECODE_WORDS}; - - use std::collections::HashSet; - - extern "C" { - fn whale_wave_reverse_abi() -> u64; - - fn whale_wave_reverse_cfg( - abi: u64, - data: *const u8, - length: u64, - base: u64, - seeds: *const u64, - seed_count: u64, - overlays: *const u64, - overlay_count: u64, - options: *const u64, - options_count: u64, - workspace: *mut u64, - workspace_words: u64, - output: *mut u64, - output_words: u64, - ) -> i32; - } - - fn limit(resource: CfgResource, limit: usize) -> CfgError { - CfgError::Limit { resource, limit: limit as u64 } - } - - fn allocated(capacity: usize) -> Result, CfgError> { - let mut v = Vec::new(); - v.try_reserve_exact(capacity).map_err(|_| CfgError::Allocation)?; - Ok(v) - } - - fn words(count: usize) -> Result, CfgError> { - let mut v = allocated(count)?; - v.resize(count, 0); - Ok(v) - } - - pub(super) fn analyze( - input: &[u8], - base: u64, - seeds: &[usize], - overlays: &[FlowOverride], - l: CfgLimits, - ) -> Result { - let max_input = l.max_input_bytes.min(16 * 1024 * 1024); - if input.len() > max_input { - return Err(limit(CfgResource::InputBytes, max_input)); - } - if base.checked_add(input.len() as u64).is_none() { - return Err(CfgError::Invalid("region address overflow")); - } - if l.max_instructions > 1_000_000 - || l.max_blocks > 1_000_000 - || l.max_edges > 4_000_000 - || l.max_stops > 1_000_000 - { - return Err(CfgError::Invalid("hard output ceiling")); - } - if seeds.len() > l.max_blocks { - return Err(limit(CfgResource::Blocks, l.max_blocks)); - } - if overlays.len() > l.max_edges || overlays.len() > 1_000_000 { - return Err(limit(CfgResource::Edges, l.max_edges.min(1_000_000))); - } - let block_base = 16 + l.max_instructions * 97; - let edge_base = block_base + l.max_blocks * 5; - let stop_base = edge_base + l.max_edges * 6; - let total_words = stop_base + l.max_stops * 4; - let workspace_words = input.len() + l.max_blocks + total_words; - let max_memory = l.max_workspace_bytes.min(512 * 1024 * 1024); - let memory = workspace_words - .checked_add(total_words) - .and_then(|n| n.checked_add(overlays.len() * 4 + seeds.len())) - .and_then(|n| n.checked_mul(8)) - .and_then(|n| n.checked_add(std::mem::size_of_val(overlays))) - .filter(|n| *n <= max_memory) - .ok_or(limit(CfgResource::Memory, max_memory))?; - let _ = memory; - // Reserve an O(n log n) normalization budget before any input scan or - // sorting. Wave receives the remaining shared analysis-work allowance. - let sort_work = |count: usize| { - (count as u64) * (u64::from(usize::BITS - count.max(1).leading_zeros()) + 1) - }; - let host_work = sort_work(seeds.len()) + sort_work(overlays.len()); - if host_work > l.max_work { - return Err(CfgError::Limit { resource: CfgResource::Work, limit: l.max_work }); - } - if seeds.iter().any(|offset| *offset >= input.len()) { - return Err(CfgError::Invalid("seed outside region")); - } - let mut normalized = allocated(overlays.len())?; - normalized.extend_from_slice(overlays); - normalized.sort_unstable_by_key(|o| o.field_offset); - let mut previous_end = 0; - for o in &normalized { - let end = o - .field_offset - .checked_add(o.width as usize) - .filter(|end| *end <= input.len()) - .ok_or(CfgError::Invalid("relocation range"))?; - if o.width == 0 || o.width > 8 || o.field_offset < previous_end { - return Err(CfgError::Invalid("overlapping or empty relocation fields")); - } - previous_end = end; - } - let mut raw_overlays = allocated(normalized.len() * 4)?; - for o in normalized { - let (kind, value) = match o.target { - CfgTarget::Unresolved => (0, 0), - CfgTarget::Address(v) => (1, v), - CfgTarget::Symbol(v) => (2, v), - }; - raw_overlays.extend_from_slice(&[o.field_offset as u64, o.width as u64, kind, value]); - } - let mut raw_seeds = allocated(seeds.len())?; - raw_seeds.extend(seeds.iter().map(|offset| *offset as u64)); - raw_seeds.sort_unstable(); - raw_seeds.dedup(); - let options = [ - l.max_instructions as u64, - l.max_blocks as u64, - l.max_edges as u64, - l.max_stops as u64, - l.max_work - host_work, - u64::from(l.follow_calls), - ]; - let mut workspace = words(workspace_words)?; - let mut output = words(total_words)?; - // SAFETY: all input/output/scratch vectors are live, disjoint and sized - // to the checked ABI formulas; indices and ranges were checked above. - // The pinned linked Wave core is trusted code and retains no pointers. - let status = unsafe { - if whale_wave_reverse_abi() != ABI_VERSION { - return Err(CfgError::Invalid("ABI version")); - } - whale_wave_reverse_cfg( - ABI_VERSION, - input.as_ptr(), - input.len() as u64, - base, - raw_seeds.as_ptr(), - raw_seeds.len() as u64, - raw_overlays.as_ptr(), - (raw_overlays.len() / 4) as u64, - options.as_ptr(), - 6, - workspace.as_mut_ptr(), - workspace_words as u64, - output.as_mut_ptr(), - total_words as u64, - ) - }; - let resource = match status { - 0 => None, - 7 => Some((CfgResource::Work, l.max_work)), - 8 => Some((CfgResource::Instructions, l.max_instructions as u64)), - 9 => Some((CfgResource::Blocks, l.max_blocks as u64)), - 10 => Some((CfgResource::Edges, l.max_edges as u64)), - 11 => Some((CfgResource::Stops, l.max_stops as u64)), - _ => return Err(CfgError::Invalid("kernel rejected input/capacity/ABI")), - }; - if let Some((resource, limit)) = resource { - return Err(CfgError::Limit { resource, limit }); - } - if output[0] != 1 - || output[1] != total_words as u64 - || output[8] != 16 - || output[9] != block_base as u64 - || output[10] != edge_base as u64 - || output[11] != stop_base as u64 - || output[6] > l.max_work - host_work - { - return Err(CfgError::Invalid("result header")); - } - let count = |at: usize, max: usize| { - usize::try_from(output[at]) - .ok() - .filter(|n| *n <= max) - .ok_or(CfgError::Invalid("result count")) - }; - let instruction_count = count(2, l.max_instructions)?; - let block_count = count(3, l.max_blocks)?; - let edge_count = count(4, l.max_edges)?; - let stop_count = count(5, l.max_stops)?; - let mut instructions = allocated(instruction_count)?; - let mut starts = HashSet::new(); - starts.try_reserve(instruction_count).map_err(|_| CfgError::Allocation)?; - for index in 0..instruction_count { - let at = 16 + index * 97; - let offset = - usize::try_from(output[at]).map_err(|_| CfgError::Invalid("instruction offset"))?; - if !starts.insert(offset) { - return Err(CfgError::Invalid("duplicate instruction")); - } - let mut record = [0; DECODE_WORDS]; - record.copy_from_slice(&output[at + 1..at + 97]); - instructions.push( - crate::decode_record(input, offset, &record).map_err(CfgError::DecodeOutput)?, - ); - } - let mut blocks = allocated(block_count)?; - let mut previous = 0; - let mut covered = 0; - for index in 0..block_count { - let at = block_base + index * 5; - let offset = - usize::try_from(output[at]).map_err(|_| CfgError::Invalid("block offset"))?; - let end = usize::try_from(output[at + 1]) - .ok() - .filter(|n| *n <= input.len()) - .ok_or(CfgError::Invalid("block end"))?; - let first = usize::try_from(output[at + 2]) - .map_err(|_| CfgError::Invalid("first instruction"))?; - let count = - usize::try_from(output[at + 3]).map_err(|_| CfgError::Invalid("block length"))?; - let last = first - .checked_add(count) - .filter(|n| *n <= instructions.len() && count > 0) - .ok_or(CfgError::Invalid("block instruction range"))?; - if offset < previous || offset >= end || instructions[first].offset != offset { - return Err(CfgError::Invalid("block ordering")); - } - let mut cursor = offset; - for instruction in &instructions[first..last] { - if instruction.offset != cursor { - return Err(CfgError::Invalid("noncontiguous block")); - } - cursor += instruction.length as usize; - } - if cursor != end { - return Err(CfgError::Invalid("block coverage")); - } - previous = end; - covered += count; - let mut instruction_indices = allocated(count)?; - instruction_indices.extend(first..last); - blocks.push(BasicBlock { offset, end, instruction_indices }); - } - if covered != instructions.len() { - return Err(CfgError::Invalid("incomplete block partition")); - } - let mut edges = allocated(edge_count)?; - for index in 0..edge_count { - let at = edge_base + index * 6; - let from = usize::try_from(output[at]) - .ok() - .filter(|n| starts.contains(n)) - .ok_or(CfgError::Invalid("edge source"))?; - let kind = match output[at + 1] { - 0 => EdgeKind::FallThrough, - 1 => EdgeKind::Call, - 2 => EdgeKind::Jump, - 3 => EdgeKind::ConditionalTaken, - 4 => EdgeKind::ConditionalFallThrough, - 5 => EdgeKind::LoopTaken, - 6 => EdgeKind::LoopFallThrough, - 7 => EdgeKind::IndirectCall, - 8 => EdgeKind::IndirectJump, - 9 => EdgeKind::Syscall, - 10 => EdgeKind::Memory, - 11 => EdgeKind::Address, - _ => return Err(CfgError::Invalid("edge kind")), - }; - let target = match output[at + 2] { - 0 => CfgTarget::Unresolved, - 1 => CfgTarget::Address(output[at + 3]), - 2 => CfgTarget::Symbol(output[at + 3]), - _ => return Err(CfgError::Invalid("edge target")), - }; - edges.push(Edge { from, kind, target }); - } - let mut stops = allocated(stop_count)?; - for index in 0..stop_count { - let at = stop_base + index * 4; - let offset = usize::try_from(output[at]) - .ok() - .filter(|n| *n <= input.len()) - .ok_or(CfgError::Invalid("stop offset"))?; - let kind = match output[at + 1] { - 1 => StopKind::Invalid, - 2 => StopKind::Truncated, - 3 => StopKind::Unsupported, - 4 => StopKind::Overlong, - 5 => StopKind::Overlap, - 6 => StopKind::EndOfRange, - 7 => StopKind::IndirectJump, - 8 => StopKind::Syscall, - 9 => StopKind::AddressOverflow, - _ => return Err(CfgError::Invalid("stop kind")), - }; - let conflict = if kind == StopKind::Overlap { - Some( - usize::try_from(output[at + 2]) - .ok() - .filter(|n| starts.contains(n)) - .ok_or(CfgError::Invalid("overlap source"))?, - ) - } else { - None - }; - stops.push(Stop { offset, kind, conflict }); - } - Ok(ControlFlowGraph { - base, - instructions, - blocks, - edges, - stops, - work: output[6] + host_work, - }) - } + Err(CfgError::CoreUnavailable) } diff --git a/reverse/src/lib.rs b/reverse/src/lib.rs index bcbdc1f..74a629b 100644 --- a/reverse/src/lib.rs +++ b/reverse/src/lib.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MPL-2.0 -//! AMD64 reverse analysis with a Wave implementation and a checked Rust boundary. -//! Ordinary builds report an unavailable core; no Rust decoder substitutes for it. +//! Bounded ELF/raw image inspection and typed reverse-analysis records. +//! Decoding and CFG analysis currently return explicit capability errors. mod cfg; mod model; @@ -11,10 +11,6 @@ pub use model::*; use std::fmt; -pub const ABI_VERSION: u64 = 1; - -pub const DECODE_WORDS: usize = 96; - #[derive(Clone, Debug, PartialEq, Eq)] pub enum DecodeError { CoreUnavailable, @@ -30,296 +26,40 @@ pub enum DecodeError { impl fmt::Display for DecodeError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { - Self::CoreUnavailable => f.write_str("Wave reverse core unavailable; build tools/build_wave_reverse.py, set WHALE_WAVE_REVERSE_DIR and enable wave-reverse"), - Self::Invalid { offset } => write!(f, "invalid AMD64 encoding or input range at byte {offset}"), + Self::CoreUnavailable => f.write_str("reverse decoder is unavailable in this build"), + Self::Invalid { offset } => { + write!(f, "invalid AMD64 encoding or input range at byte {offset}") + }, Self::Truncated { offset } => write!(f, "truncated AMD64 instruction at byte {offset}"), - Self::Unsupported { offset } => write!(f, "unsupported AMD64 encoding at byte {offset}"), - Self::Overlong { offset } => write!(f, "AMD64 instruction exceeds 15 bytes at byte {offset}"), - Self::Capacity => f.write_str("Wave reverse output capacity exhausted"), - Self::AbiMismatch { expected, actual } => write!(f, "Wave reverse ABI mismatch: expected {expected}, got {actual}"), - Self::InvalidOutput(reason) => write!(f, "invalid Wave reverse result: {reason}"), + Self::Unsupported { offset } => { + write!(f, "unsupported AMD64 encoding at byte {offset}") + }, + Self::Overlong { offset } => { + write!(f, "AMD64 instruction exceeds 15 bytes at byte {offset}") + }, + Self::Capacity => f.write_str("reverse output capacity exhausted"), + Self::AbiMismatch { expected, actual } => { + write!(f, "reverse ABI mismatch: expected {expected}, got {actual}") + }, + Self::InvalidOutput(reason) => write!(f, "invalid reverse result: {reason}"), } } } impl std::error::Error for DecodeError {} +/// Whether instruction decoding and control-flow analysis are available. pub const fn backend_available() -> bool { - cfg!(whale_wave_reverse) + false } pub const fn backend_name() -> &'static str { - if backend_available() { - "wave-llvm-bootstrap" - } else { - "unavailable" - } -} - -#[cfg(whale_wave_reverse)] -extern "C" { - fn whale_wave_reverse_abi() -> u64; - - fn whale_wave_reverse_decode( - abi: u64, - input: *const u8, - length: u64, - offset: u64, - output: *mut u64, - capacity: u64, - ) -> i32; -} - -/// Decode one instruction at a checked slice offset. Input and its original bytes -/// remain caller-owned; any failure publishes no partial instruction. -pub fn decode(input: &[u8], offset: usize) -> Result { - #[cfg(not(whale_wave_reverse))] - { - let _ = (input, offset); - Err(DecodeError::CoreUnavailable) - } - #[cfg(whale_wave_reverse)] - { - if offset > input.len() { - return Err(DecodeError::Invalid { offset }); - } - // SAFETY: the fixed no-argument capability entry has no memory operands. - let actual = unsafe { whale_wave_reverse_abi() }; - if actual != ABI_VERSION { - return Err(DecodeError::AbiMismatch { expected: ABI_VERSION, actual }); - } - let mut record = [0u64; DECODE_WORDS]; - // SAFETY: both buffers live through this call, output is aligned and has - // exactly DECODE_WORDS writable words, and offset is inside the input. - // ABI1 requires the kernel to read <=15 bytes inside the supplied slice - // and to commit output only after complete success. The linked, pinned - // Wave archive is trusted implementation code, not an untrusted plugin. - let status = unsafe { - whale_wave_reverse_decode( - ABI_VERSION, - input.as_ptr(), - input.len() as u64, - offset as u64, - record.as_mut_ptr(), - DECODE_WORDS as u64, - ) - }; - match status { - 0 => decode_record(input, offset, &record), - 1 => Err(DecodeError::Invalid { offset }), - 2 => Err(DecodeError::Truncated { offset }), - 3 => Err(DecodeError::Unsupported { offset }), - 4 => Err(DecodeError::Overlong { offset }), - 5 => Err(DecodeError::Capacity), - 6 => Err(DecodeError::AbiMismatch { expected: ABI_VERSION, actual }), - _ => Err(DecodeError::InvalidOutput("unknown status")), - } - } + "unavailable" } -#[cfg(whale_wave_reverse)] -fn decode_record( - input: &[u8], - offset: usize, - r: &[u64; DECODE_WORDS], -) -> Result { - let bad = DecodeError::InvalidOutput; - if r[0] != ABI_VERSION || r[1] != DECODE_WORDS as u64 { - return Err(bad("record header")); - } - let length = u8::try_from(r[2]).map_err(|_| bad("instruction length"))?; - if !(1..=15).contains(&length) { - return Err(bad("instruction length")); - } - let end = offset - .checked_add(length as usize) - .filter(|end| *end <= input.len()) - .ok_or(bad("input range"))?; - let bytes = &input[offset..end]; - let mut original = [0; 15]; - original[..bytes.len()].copy_from_slice(bytes); - let opcode = Opcode::from_code(r[3]).ok_or(bad("opcode"))?; - let condition = - if r[4] == 16 { None } else { Some(Condition::from_code(r[4]).ok_or(bad("condition"))?) }; - if condition.is_some() != matches!(opcode, Opcode::Jcc | Opcode::Setcc | Opcode::Cmovcc) { - return Err(bad("condition opcode")); - } - let operand_count = - usize::try_from(r[5]).ok().filter(|n| *n <= 3).ok_or(bad("operand count"))?; - let prefix_count = - usize::try_from(r[7]).ok().filter(|n| *n < bytes.len()).ok_or(bad("prefix count"))?; - if r[8] != prefix_count as u64 || !matches!(r[9], 1 | 2) || r[8] + r[9] > u64::from(length) { - return Err(bad("opcode range")); - } - let mut prefixes = Vec::with_capacity(prefix_count); - for (i, byte) in bytes.iter().take(prefix_count).enumerate() { - if r[24 + i] != u64::from(*byte) { - return Err(bad("prefix bytes")); - } - prefixes.push(*byte); - } - let rex = if r[20] == 0 { - None - } else { - Some( - u8::try_from(r[20]) - .ok() - .filter(|b| (0x40..=0x4f).contains(b)) - .ok_or(bad("REX byte"))?, - ) - }; - let byte_field = |at: usize| -> Result, DecodeError> { - if r[at] == 0 { - return Ok(None); - } - let off = usize::try_from(r[at] - 1) - .ok() - .filter(|n| *n < bytes.len()) - .ok_or(bad("encoding byte range"))?; - if r[at + 1] != u64::from(bytes[off]) { - return Err(bad("encoding byte bits")); - } - Ok(Some(EncodingByte { offset: off as u8, value: bytes[off] })) - }; - let field = |at: usize| -> Result, DecodeError> { - if r[at] == 0 { - return Ok(None); - } - let off = usize::try_from(r[at] - 1).map_err(|_| bad("field offset"))?; - let width = usize::try_from(r[at + 1]) - .ok() - .filter(|n| matches!(n, 1 | 2 | 4 | 8)) - .ok_or(bad("field width"))?; - let end = off.checked_add(width).filter(|n| *n <= bytes.len()).ok_or(bad("field range"))?; - let bits = bytes[off..end] - .iter() - .enumerate() - .fold(0u64, |v, (i, b)| v | (u64::from(*b) << (i * 8))); - if bits != r[at + 2] { - return Err(bad("field bits")); - } - Ok(Some(EncodingField { offset: off as u8, width: width as u8, bits })) - }; - let encoding = Encoding { - prefixes, - rex, - opcode_offset: r[8] as u8, - opcode_len: r[9] as u8, - modrm: byte_field(10)?, - sib: byte_field(12)?, - displacement: field(14)?, - immediate: field(17)?, - }; - let mut operands = Vec::with_capacity(operand_count); - let gpr = |code: u64| -> Result { - let index = u8::try_from(code).ok().filter(|n| *n < 16).ok_or(bad("address register"))?; - Ok(Register { class: RegisterClass::General, index, width: 64, high8: false }) - }; - for operand in 0..operand_count { - let at = 40 + operand * 16; - let width = u16::try_from(r[at + 1]).map_err(|_| bad("operand width"))?; - let value = match r[at] { - kind @ (1 | 2) => { - let index = u8::try_from(r[at + 2]) - .ok() - .filter(|n| *n < 16) - .ok_or(bad("register index"))?; - let high8 = match r[at + 3] { - 0 => false, - 1 => true, - _ => return Err(bad("high byte flag")), - }; - if kind == 1 - && (!matches!(width, 8 | 16 | 32 | 64) - || (high8 && (width != 8 || index >= 4 || rex.is_some()))) - { - return Err(bad("GPR shape")); - } - if kind == 2 && (width != 128 || high8) { - return Err(bad("XMM shape")); - } - Operand::Register(Register { - class: if kind == 1 { RegisterClass::General } else { RegisterClass::Xmm }, - index, - width, - high8, - }) - }, - 3 => { - if !matches!(width, 8 | 16 | 32 | 64) { - return Err(bad("memory width")); - } - let base = match r[at + 2] { - 0 | 17 => None, - code @ 1..=16 => Some(gpr(code - 1)?), - _ => return Err(bad("memory base")), - }; - let index = match r[at + 3] { - 0 => None, - code @ 1..=16 => Some(gpr(code - 1)?), - _ => return Err(bad("memory index")), - }; - let scale = u8::try_from(r[at + 4]) - .ok() - .filter(|n| matches!(n, 1 | 2 | 4 | 8)) - .ok_or(bad("memory scale"))?; - Operand::Memory(MemoryOperand { - width, - base, - index, - scale, - displacement: r[at + 5] as i64, - rip_relative: r[at + 2] == 17, - }) - }, - 4 => { - let encoded_width = u8::try_from(r[at + 6]) - .ok() - .filter(|n| matches!(n, 0 | 8 | 16 | 32 | 64)) - .ok_or(bad("immediate width"))?; - if !matches!(width, 8 | 16 | 32 | 64) || r[at + 3] > 1 { - return Err(bad("immediate shape")); - } - Operand::Immediate(Immediate { - value: r[at + 2], - width, - encoded_width, - sign_extended: r[at + 3] == 1, - }) - }, - 5 => { - let encoded_width = u8::try_from(r[at + 6]) - .ok() - .filter(|n| matches!(n, 8 | 32)) - .ok_or(bad("relative width"))?; - Operand::Relative(Relative { displacement: r[at + 2] as i64, encoded_width }) - }, - _ => return Err(bad("operand kind")), - }; - operands.push(value); - } - let relative = operands.iter().find_map(|o| { - if let Operand::Relative(r) = o { - Some(r.displacement) - } else { - None - } - }); - let required = || relative.ok_or(bad("missing relative operand")); - let flow = match r[6] { - 0 => Flow::FallThrough, - 1 => Flow::Call { relative: Some(required()?) }, - 2 => Flow::Call { relative: None }, - 3 => Flow::Jump { relative: Some(required()?) }, - 4 => Flow::Jump { relative: None }, - 5 => Flow::Conditional { relative: required()? }, - 6 => Flow::Loop { relative: required()? }, - 7 => Flow::Return, - 8 => Flow::Trap, - 9 => Flow::Syscall, - _ => return Err(bad("flow kind")), - }; - Ok(Instruction { offset, length, bytes: original, opcode, condition, operands, encoding, flow }) +/// Report the missing decoding capability without interpreting input bytes. +pub fn decode(_input: &[u8], _offset: usize) -> Result { + Err(DecodeError::CoreUnavailable) } pub mod format; diff --git a/reverse/src/model.rs b/reverse/src/model.rs index 0a0cdc1..fce204e 100644 --- a/reverse/src/model.rs +++ b/reverse/src/model.rs @@ -103,60 +103,6 @@ impl Opcode { Self::Divsd => "divsd", } } - - #[cfg(whale_wave_reverse)] - pub(crate) fn from_code(code: u64) -> Option { - Some(match code { - 1 => Self::Mov, - 2 => Self::Add, - 3 => Self::Or, - 4 => Self::Adc, - 5 => Self::Sbb, - 6 => Self::And, - 7 => Self::Sub, - 8 => Self::Xor, - 9 => Self::Cmp, - 10 => Self::Imul, - 11 => Self::Push, - 12 => Self::Pop, - 13 => Self::Jmp, - 14 => Self::Jcc, - 15 => Self::Loop, - 16 => Self::Call, - 17 => Self::Ret, - 18 => Self::Nop, - 19 => Self::Syscall, - 20 => Self::Int3, - 21 => Self::Lea, - 22 => Self::Test, - 23 => Self::Not, - 24 => Self::Neg, - 25 => Self::Div, - 26 => Self::Idiv, - 27 => Self::Shl, - 28 => Self::Shr, - 29 => Self::Sar, - 30 => Self::Cwd, - 31 => Self::Cdq, - 32 => Self::Cqo, - 33 => Self::Movzx, - 34 => Self::Movsx, - 35 => Self::Movsxd, - 36 => Self::Setcc, - 37 => Self::Cmovcc, - 38 => Self::Movss, - 39 => Self::Movsd, - 40 => Self::Addss, - 41 => Self::Addsd, - 42 => Self::Subss, - 43 => Self::Subsd, - 44 => Self::Mulss, - 45 => Self::Mulsd, - 46 => Self::Divss, - 47 => Self::Divsd, - _ => return None, - }) - } } #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -185,29 +131,6 @@ impl Condition { ["o", "no", "b", "ae", "e", "ne", "be", "a", "s", "ns", "p", "np", "l", "ge", "le", "g"] [self as usize] } - - #[cfg(whale_wave_reverse)] - pub(crate) fn from_code(code: u64) -> Option { - Some(match code { - 0 => Self::O, - 1 => Self::No, - 2 => Self::B, - 3 => Self::Ae, - 4 => Self::E, - 5 => Self::Ne, - 6 => Self::Be, - 7 => Self::A, - 8 => Self::S, - 9 => Self::Ns, - 10 => Self::P, - 11 => Self::Np, - 12 => Self::L, - 13 => Self::Ge, - 14 => Self::Le, - 15 => Self::G, - _ => return None, - }) - } } #[derive(Clone, Copy, Debug, PartialEq, Eq)] diff --git a/reverse/tests/cfg.rs b/reverse/tests/cfg.rs index e260ac9..f642de3 100644 --- a/reverse/tests/cfg.rs +++ b/reverse/tests/cfg.rs @@ -2,374 +2,12 @@ use reverse::*; #[test] fn absent_cfg_core_is_explicit() { - if !backend_available() { + assert!(!backend_available()); + for (bytes, base, seeds) in [(&[0xc3][..], 0, &[0][..]), (&[][..], u64::MAX, &[usize::MAX][..])] + { assert_eq!( - analyze(&[0xc3], 0, &[0], &[], CfgLimits::default()), + analyze(bytes, base, seeds, &[], CfgLimits::default()), Err(CfgError::CoreUnavailable) ); } } - -#[cfg(whale_wave_reverse)] -mod native { - use super::*; - - fn limits() -> CfgLimits { - CfgLimits { - max_input_bytes: 65536, - max_instructions: 256, - max_blocks: 128, - max_edges: 1024, - max_stops: 128, - max_work: 1_000_000, - max_workspace_bytes: 4 * 1024 * 1024, - follow_calls: true, - } - } - - fn graph(bytes: &[u8], seeds: &[usize]) -> ControlFlowGraph { - analyze(bytes, 0x1000, seeds, &[], limits()).unwrap() - } - - fn offsets(g: &ControlFlowGraph) -> Vec { - let mut v: Vec<_> = g.instructions.iter().map(|i| i.offset).collect(); - v.sort_unstable(); - v - } - - fn edge(g: &ControlFlowGraph, from: usize, kind: EdgeKind, target: CfgTarget) { - assert!( - g.edges.contains(&Edge { from, kind, target }), - "missing edge {from} {kind:?} {target:?}: {:?}", - g.edges - ); - } - - #[test] - fn rex_w_push_immediate_bytes_do_not_become_fake_return_boundaries() { - let g = graph(&[0x66, 0x48, 0x68, 0x34, 0x12, 0xc3, 0x56, 0xc3], &[0]); - assert_eq!(offsets(&g), [0, 7]); - assert_eq!(g.blocks.iter().map(|b| (b.offset, b.end)).collect::>(), [(0, 8)]); - assert!(g.stops.is_empty()); - } - - #[test] - fn diamond_and_late_backward_leaders_split_existing_blocks_in_wave() { - let g = graph(&[0x75, 3, 0x90, 0xeb, 1, 0x90, 0xc3], &[0]); - assert_eq!(offsets(&g), [0, 2, 3, 5, 6]); - assert_eq!( - g.blocks.iter().map(|b| (b.offset, b.end)).collect::>(), - [(0, 2), (2, 5), (5, 6), (6, 7)] - ); - edge(&g, 0, EdgeKind::ConditionalTaken, CfgTarget::Address(0x1005)); - edge(&g, 0, EdgeKind::ConditionalFallThrough, CfgTarget::Address(0x1002)); - edge(&g, 3, EdgeKind::Jump, CfgTarget::Address(0x1006)); - edge(&g, 5, EdgeKind::FallThrough, CfgTarget::Address(0x1006)); - assert!(g.stops.is_empty()); - let g = graph(&[0x90, 0x90, 0x90, 0xeb, 0xfc], &[0]); - assert_eq!( - g.blocks.iter().map(|b| (b.offset, b.end)).collect::>(), - [(0, 1), (1, 5)] - ); - edge(&g, 0, EdgeKind::FallThrough, CfgTarget::Address(0x1001)); - edge(&g, 3, EdgeKind::Jump, CfgTarget::Address(0x1001)); - } - - #[test] - fn entries_decode_backward_callees_and_targets_after_unsupported_gaps_on_demand() { - let bytes = [0xc3, 0x0f, 0x0b, 0x90, 0xe8, 0xf7, 0xff, 0xff, 0xff, 0xc3]; - let g = graph(&bytes, &[4]); - assert_eq!(offsets(&g), [0, 4, 9]); - edge(&g, 4, EdgeKind::Call, CfgTarget::Address(0x1000)); - let g = analyze(&bytes, 0x1000, &[4], &[], CfgLimits { follow_calls: false, ..limits() }) - .unwrap(); - assert_eq!(offsets(&g), [4, 9]); - let g = graph(&[0xeb, 2, 0x0f, 0x0b, 0x90, 0xc3], &[0]); - assert_eq!(offsets(&g), [0, 4, 5]); - assert!(g.stops.is_empty()); - } - - #[test] - fn recursive_calls_and_indirect_targets_have_bounded_explicit_edges() { - let g = graph(&[0xe8, 0xfb, 0xff, 0xff, 0xff, 0xc3], &[0]); - assert_eq!(offsets(&g), [0, 5]); - edge(&g, 0, EdgeKind::Call, CfgTarget::Address(0x1000)); - let g = graph(&[0xff, 0xd0, 0xff, 0xe0, 0x90, 0xc3], &[0]); - assert_eq!(offsets(&g), [0, 2]); - edge(&g, 0, EdgeKind::IndirectCall, CfgTarget::Unresolved); - edge(&g, 2, EdgeKind::IndirectJump, CfgTarget::Unresolved); - assert!(g.stops.iter().any(|s| s.kind == StopKind::IndirectJump && s.offset == 2)); - let g = graph(&[0x0f, 5, 0xc3], &[0]); - assert_eq!(offsets(&g), [0]); - edge(&g, 0, EdgeKind::Syscall, CfgTarget::Unresolved); - assert_eq!(g.stops[0].kind, StopKind::Syscall); - } - - #[test] - fn unknown_truncated_invalid_overlong_and_overlapping_entries_stop_without_guessing() { - for (bytes, kind) in [ - (vec![0xc5], StopKind::Unsupported), - (vec![0x48, 0xb8], StopKind::Truncated), - (vec![0x8d, 0xc0], StopKind::Invalid), - (vec![0x66; 15], StopKind::Overlong), - ] { - let g = graph(&bytes, &[0]); - assert!(g.instructions.is_empty()); - assert!(g.blocks.is_empty()); - assert_eq!(g.stops[0].kind, kind); - } - let g = graph(&[0xeb, 0xff], &[0]); - assert_eq!(offsets(&g), [0]); - assert!(g.stops.contains(&Stop { offset: 1, kind: StopKind::Overlap, conflict: Some(0) })); - let g = graph(&[0xb8, 0x90, 0xc3, 0, 0, 0xe9, 0xf6, 0xff, 0xff, 0xff], &[2, 5]); - assert_eq!(offsets(&g), [2, 5]); - assert!(g.stops.contains(&Stop { offset: 0, kind: StopKind::Overlap, conflict: Some(2) })); - } - - #[test] - fn relocation_overlays_override_placeholders_before_target_selection() { - let bytes = [0xe8, 0, 0, 0, 0, 0xc3, 0x0f, 0x0b, 0xc3]; - let overlay = FlowOverride { field_offset: 1, width: 4, target: CfgTarget::Symbol(77) }; - let g = analyze(&bytes, 0x1000, &[0], &[overlay], limits()).unwrap(); - assert_eq!(offsets(&g), [0, 5]); - edge(&g, 0, EdgeKind::Call, CfgTarget::Symbol(77)); - assert!(!g - .edges - .iter() - .any(|e| e.kind == EdgeKind::Call && e.target == CfgTarget::Address(0x1005))); - let g = analyze( - &bytes, - 0x1000, - &[0], - &[FlowOverride { target: CfgTarget::Address(0x1008), ..overlay }], - limits(), - ) - .unwrap(); - assert_eq!(offsets(&g), [0, 5, 8]); - let g = analyze( - &bytes, - 0x1000, - &[0], - &[FlowOverride { field_offset: 2, width: 2, target: CfgTarget::Address(0x1008) }], - limits(), - ) - .unwrap(); - edge(&g, 0, EdgeKind::Call, CfgTarget::Unresolved); - assert_eq!(offsets(&g), [0, 5]); - let g = analyze( - &bytes, - 0x1000, - &[0], - &[FlowOverride { target: CfgTarget::Unresolved, ..overlay }], - limits(), - ) - .unwrap(); - edge(&g, 0, EdgeKind::Call, CfgTarget::Unresolved); - assert!(g.stops.iter().all(|s| s.kind != StopKind::AddressOverflow)); - } - - #[test] - fn memory_and_symbolic_immediate_xrefs_do_not_fabricate_code_reachability() { - let bytes = [0x48, 0x8b, 0x05, 2, 0, 0, 0, 0xc3, 0x90, 0x90]; - let g = graph(&bytes, &[0]); - assert_eq!(offsets(&g), [0, 7]); - edge(&g, 0, EdgeKind::Memory, CfgTarget::Address(0x1009)); - let g = analyze( - &bytes, - 0x1000, - &[0], - &[FlowOverride { field_offset: 3, width: 4, target: CfgTarget::Symbol(9) }], - limits(), - ) - .unwrap(); - edge(&g, 0, EdgeKind::Memory, CfgTarget::Symbol(9)); - let g = graph(&[0x48, 0x8b, 0x04, 0x25, 0xfc, 0xff, 0xff, 0xff, 0xc3], &[0]); - edge(&g, 0, EdgeKind::Memory, CfgTarget::Address(u64::MAX - 3)); - let g = graph(&[0x48, 0x8d, 0x05, 0, 0, 0, 0, 0xc3], &[0]); - edge(&g, 0, EdgeKind::Address, CfgTarget::Address(0x1007)); - let bytes = [0xb8, 0, 0, 0, 0, 0xc3]; - let g = graph(&bytes, &[0]); - assert!(g.edges.is_empty()); - let g = analyze( - &bytes, - 0x1000, - &[0], - &[FlowOverride { field_offset: 1, width: 4, target: CfgTarget::Symbol(3) }], - limits(), - ) - .unwrap(); - edge(&g, 0, EdgeKind::Address, CfgTarget::Symbol(3)); - } - - #[test] - fn indexed_symbol_components_are_xrefs_without_becoming_effective_code_addresses() { - let bytes = [0x48, 0x8b, 4, 0x85, 0, 0, 0, 0, 0xc3]; - let g = graph(&bytes, &[0]); - assert!(g.edges.is_empty()); - let g = analyze( - &bytes, - 0x1000, - &[0], - &[FlowOverride { field_offset: 4, width: 4, target: CfgTarget::Symbol(42) }], - limits(), - ) - .unwrap(); - edge(&g, 0, EdgeKind::Memory, CfgTarget::Symbol(42)); - assert_eq!(offsets(&g), [0, 8]); - } - - #[test] - fn rip_references_include_trailing_immediates_and_never_resolve_indirect_contents() { - let g = graph(&[0xc7, 5, 0, 0, 0, 0, 1, 0, 0, 0, 0xc3], &[0]); - edge(&g, 0, EdgeKind::Memory, CfgTarget::Address(0x100a)); - let g = graph(&[0xff, 0x25, 0, 0, 0, 0, 0xc3], &[0]); - assert_eq!(offsets(&g), [0]); - edge(&g, 0, EdgeKind::Memory, CfgTarget::Address(0x1006)); - edge(&g, 0, EdgeKind::IndirectJump, CfgTarget::Unresolved); - } - - #[test] - fn large_overlay_sets_use_shared_normalization_and_binary_lookup_budgets() { - let mut bytes = Vec::new(); - let mut overlays = Vec::new(); - for index in 0..256 { - overlays.push(FlowOverride { - field_offset: bytes.len() + 1, - width: 4, - target: CfgTarget::Symbol(index), - }); - bytes.extend_from_slice(&[0xe8, 0, 0, 0, 0]); - } - bytes.push(0xc3); - for index in 0..1000 { - overlays.push(FlowOverride { - field_offset: bytes.len(), - width: 1, - target: CfgTarget::Symbol(1000 + index), - }); - bytes.push(0x90); - } - let budget = CfgLimits { - max_instructions: 300, - max_blocks: 300, - max_edges: 1600, - max_work: 70_000, - ..limits() - }; - let g = analyze(&bytes, 0, &[0], &overlays, budget).unwrap(); - assert_eq!(g.instructions.len(), 257); - assert_eq!(g.edges.len(), 512); - assert!(g.work <= 70_000); - assert!(matches!( - analyze(&bytes, 0, &[0], &overlays, CfgLimits { max_work: 1256, ..budget }), - Err(CfgError::Limit { resource: CfgResource::Work, .. }) - )); - } - - #[test] - fn scope_address_overflow_and_end_of_region_are_explicit() { - let g = graph(&[0xeb, 0x7f], &[0]); - assert_eq!(offsets(&g), [0]); - edge(&g, 0, EdgeKind::Jump, CfgTarget::Address(0x1081)); - let g = analyze(&[0xeb, 0x7f], u64::MAX - 2, &[0], &[], limits()).unwrap(); - edge(&g, 0, EdgeKind::Jump, CfgTarget::Unresolved); - assert_eq!(g.stops[0].kind, StopKind::AddressOverflow); - assert!(matches!( - analyze(&[0xc3, 0xc3], u64::MAX, &[0], &[], limits()), - Err(CfgError::Invalid(_)) - )); - let g = graph(&[0x90], &[0]); - assert_eq!(g.stops[0].kind, StopKind::EndOfRange); - edge(&g, 0, EdgeKind::FallThrough, CfgTarget::Address(0x1001)); - } - - #[test] - fn every_resource_budget_and_invalid_boundary_has_a_structured_error() { - for (resource, limits, bytes) in [ - (CfgResource::InputBytes, CfgLimits { max_input_bytes: 0, ..limits() }, vec![0xc3]), - (CfgResource::Instructions, CfgLimits { max_instructions: 0, ..limits() }, vec![0xc3]), - (CfgResource::Blocks, CfgLimits { max_blocks: 0, ..limits() }, vec![0xc3]), - (CfgResource::Edges, CfgLimits { max_edges: 0, ..limits() }, vec![0xeb, 0]), - (CfgResource::Stops, CfgLimits { max_stops: 0, ..limits() }, vec![0xc5]), - (CfgResource::Work, CfgLimits { max_work: 0, ..limits() }, vec![0xc3]), - (CfgResource::Memory, CfgLimits { max_workspace_bytes: 0, ..limits() }, vec![0xc3]), - ] { - assert!( - matches!(analyze(&bytes,0,&[0],&[],limits),Err(CfgError::Limit{resource:r,..}) if r==resource), - "{resource:?}" - ); - } - assert!(matches!(analyze(&[0xc3], 0, &[1], &[], limits()), Err(CfgError::Invalid(_)))); - let overlays = [ - FlowOverride { field_offset: 1, width: 4, target: CfgTarget::Symbol(0) }, - FlowOverride { field_offset: 2, width: 1, target: CfgTarget::Symbol(1) }, - ]; - assert!(matches!( - analyze(&[0xe8, 0, 0, 0, 0, 0xc3], 0, &[0], &overlays, limits()), - Err(CfgError::Invalid(_)) - )); - } - - #[test] - fn seed_and_overlay_normalization_is_deterministic() { - let bytes = [0xb8, 0, 0, 0, 0, 0xc3, 0xb8, 0, 0, 0, 0, 0xc3]; - let a = FlowOverride { field_offset: 1, width: 4, target: CfgTarget::Symbol(1) }; - let b = FlowOverride { field_offset: 7, width: 4, target: CfgTarget::Symbol(2) }; - let first = analyze(&bytes, 0, &[6, 0], &[b, a], limits()).unwrap(); - let second = analyze(&bytes, 0, &[0, 6], &[a, b], limits()).unwrap(); - assert_eq!(first, second); - } - - #[test] - fn raw_cfg_failures_never_publish_partial_graph_output() { - extern "C" { - fn whale_wave_reverse_cfg( - abi: u64, - data: *const u8, - length: u64, - base: u64, - seeds: *const u64, - seed_count: u64, - overlays: *const u64, - overlay_count: u64, - options: *const u64, - options_count: u64, - workspace: *mut u64, - workspace_words: u64, - output: *mut u64, - output_words: u64, - ) -> i32; - } - let bytes = [0xc3u8]; - let seeds = [0u64]; - for (abi, max_work, capacity, expected) in - [(0, 1000, 488, 6), (1, 0, 488, 7), (1, 1000, 0, 5)] - { - let options = [4u64, 4, 8, 4, max_work, 1]; - let total = 16 + 4 * 97 + 4 * 5 + 8 * 6 + 4 * 4; - let mut workspace = vec![0u64; 1 + 4 + total]; - let mut output = vec![u64::MAX; total]; - // SAFETY: valid disjoint aligned buffers, scalar rejection cases. - let status = unsafe { - whale_wave_reverse_cfg( - abi, - bytes.as_ptr(), - 1, - 0, - seeds.as_ptr(), - 1, - std::ptr::null(), - 0, - options.as_ptr(), - 6, - workspace.as_mut_ptr(), - workspace.len() as u64, - output.as_mut_ptr(), - capacity, - ) - }; - assert_eq!(status, expected); - assert!(output.iter().all(|v| *v == u64::MAX)); - } - } -} diff --git a/reverse/tests/decode.rs b/reverse/tests/decode.rs index 5c7c66f..17bfb51 100644 --- a/reverse/tests/decode.rs +++ b/reverse/tests/decode.rs @@ -2,489 +2,9 @@ use reverse::*; #[test] fn absent_core_has_an_explicit_capability_error() { - if !backend_available() { - assert_eq!(decode(&[0x90], 0), Err(DecodeError::CoreUnavailable)); - assert_eq!(backend_name(), "unavailable"); - } -} - -#[cfg(whale_wave_reverse)] -mod native { - use super::*; - - use amd64::AMD64; - - use assembler::assemble; - - fn one(bytes: &[u8]) -> Instruction { - let instruction = decode(bytes, 0).unwrap_or_else(|e| panic!("{bytes:02x?}: {e}")); - assert_eq!(instruction.length as usize, bytes.len()); - assert_eq!(instruction.original_bytes(), bytes); - instruction - } - - fn reg(operand: Operand, name: &str) { - let Operand::Register(r) = operand else { panic!("expected {name}: {operand:?}") }; - assert_eq!(r.name(), name); - } - - fn encoded(source: &str) -> Vec { - assemble(source, &AMD64).unwrap_or_else(|e| panic!("{source}: {e}")).sections.remove(0).data - } - - #[test] - fn manual_integer_fields_preserve_widths_signedness_and_high_byte_rules() { - let x = one(&[0x48, 0xb8, 0xef, 0xcd, 0xab, 0x89, 0x67, 0x45, 0x23, 0x01]); - assert_eq!(x.opcode, Opcode::Mov); - reg(x.operands[0], "rax"); - assert_eq!( - x.encoding.immediate, - Some(EncodingField { offset: 2, width: 8, bits: 0x0123456789abcdef }) - ); - let x = one(&[0x66, 0x41, 0xb9, 0x34, 0x12]); - reg(x.operands[0], "r9w"); - assert_eq!(x.encoding.immediate.unwrap().width, 2); - let x = one(&[0x48, 0xc7, 0xc0, 0xff, 0xff, 0xff, 0xff]); - let Operand::Immediate(i) = x.operands[1] else { panic!() }; - assert_eq!( - (i.width, i.encoded_width, i.sign_extended, i.signed_value()), - (64, 32, true, -1) - ); - for (bytes, dst, src) in [ - (vec![0x88, 0xe0], "al", "ah"), - (vec![0x40, 0x88, 0xe0], "al", "spl"), - (vec![0x41, 0x88, 0xe0], "r8b", "spl"), - (vec![0x0f, 0xb6, 0xc4], "eax", "ah"), - (vec![0x44, 0x0f, 0xb6, 0xc4], "r8d", "spl"), - // An intervening legacy prefix cancels the earlier REX. - (vec![0x40, 0x66, 0x88, 0xe0], "al", "ah"), - ] { - let x = one(&bytes); - reg(x.operands[0], dst); - reg(x.operands[1], src); - } - for (bytes, name, width) in [ - (vec![0x50], "rax", 64), - (vec![0x41, 0x50], "r8", 64), - (vec![0x66, 0x41, 0x50], "r8w", 16), - (vec![0x48, 0x58], "rax", 64), - ] { - let x = one(&bytes); - reg(x.operands[0], name); - let Operand::Register(r) = x.operands[0] else { panic!() }; - assert_eq!(r.width, width); - } - let x = one(&[0x66, 0x68, 0, 0x80]); - assert!(matches!( - x.operands[0], - Operand::Immediate(Immediate { - width: 16, - encoded_width: 16, - sign_extended: false, - .. - }) - )); - let x = one(&[0x6a, 0xff]); - let Operand::Immediate(i) = x.operands[0] else { panic!() }; - assert_eq!((i.width, i.encoded_width, i.signed_value()), (64, 8, -1)); - let x = one(&[0x48, 0xd1, 0xe0]); - assert!(x.encoding.immediate.is_none()); - assert!(matches!( - x.operands[1], - Operand::Immediate(Immediate { value: 1, encoded_width: 0, .. }) - )); - } - - #[test] - fn stack_operand_size_honors_effective_rex_w_and_legacy_cancellation() { - for opcode in [0x50, 0x58] { - for (prefix, name, width) in [ - (vec![0x66, 0x48], "rax", 64), - (vec![0x66, 0x49], "r8", 64), - (vec![0x66], "ax", 16), - (vec![0x48, 0x66], "ax", 16), - (vec![0x66, 0x40], "ax", 16), - ] { - let mut bytes = prefix; - bytes.push(opcode); - let x = one(&bytes); - reg(x.operands[0], name); - assert!(matches!(x.operands[0], Operand::Register(r) if r.width == width)); - } - } - for (bytes, width, encoded_width, sign_extended) in [ - (vec![0x66, 0x48, 0x68, 0x34, 0x12, 0xc3, 0x56], 64, 32, true), - (vec![0x66, 0x48, 0x6a, 0xff], 64, 8, true), - (vec![0x48, 0x66, 0x68, 0x34, 0x12], 16, 16, false), - (vec![0x66, 0x40, 0x68, 0x34, 0x12], 16, 16, false), - (vec![0x66, 0x6a, 0xff], 16, 8, true), - ] { - let x = one(&bytes); - assert!(matches!(x.operands[0], Operand::Immediate(i) if - (i.width, i.encoded_width, i.sign_extended) == (width, encoded_width, sign_extended))); - } - } - - #[test] - fn manual_sib_rip_absolute_and_rex_sentinels_are_distinct() { - let x = one(&[0x4b, 0x8b, 0x44, 0xcc, 0x80]); - reg(x.operands[0], "rax"); - let Operand::Memory(m) = x.operands[1] else { panic!() }; - assert_eq!(m.base.unwrap().name(), "r12"); - assert_eq!(m.index.unwrap().name(), "r9"); - assert_eq!((m.scale, m.displacement, m.rip_relative), (8, -128, false)); - assert_eq!(x.encoding.modrm, Some(EncodingByte { offset: 2, value: 0x44 })); - assert_eq!(x.encoding.sib, Some(EncodingByte { offset: 3, value: 0xcc })); - assert_eq!( - x.encoding.displacement, - Some(EncodingField { offset: 4, width: 1, bits: 0x80 }) - ); - for rex in [0x48, 0x49] { - let x = one(&[rex, 0x8b, 0x05, 0xfc, 0xff, 0xff, 0xff]); - let Operand::Memory(m) = x.operands[1] else { panic!() }; - assert!(m.rip_relative); - assert!(m.base.is_none()); - assert_eq!(m.displacement, -4); - let x = one(&[rex, 0x8b, 0x04, 0x25, 0xfc, 0xff, 0xff, 0xff]); - let Operand::Memory(m) = x.operands[1] else { panic!() }; - assert!(!m.rip_relative); - assert!(m.base.is_none()); - assert!(m.index.is_none()); - assert_eq!(m.displacement, -4); - } - let x = one(&[0x4a, 0x8b, 0x04, 0x25, 0, 0, 0, 0]); - let Operand::Memory(m) = x.operands[1] else { panic!() }; - assert_eq!(m.index.unwrap().name(), "r12"); - } - - #[test] - fn direct_indirect_conditional_and_loop_flow_keep_the_encoding_target_contract() { - for (bytes, flow, displacement, width) in [ - (vec![0xe8, 0xfb, 0xff, 0xff, 0xff], "call", -5, 32), - (vec![0xeb, 0xfe], "jmp", -2, 8), - (vec![0x0f, 0x85, 1, 0, 0, 0], "jne", 1, 32), - (vec![0xe2, 0xfc], "loop", -4, 8), - ] { - let x = one(&bytes); - assert_eq!(x.mnemonic(), flow); - assert_eq!(x.flow.relative(), Some(displacement)); - assert!( - matches!(x.operands[0],Operand::Relative(r) if r.displacement==displacement && r.encoded_width==width) - ); - } - let x = one(&[0x41, 0xff, 0xd0]); - assert_eq!(x.flow, Flow::Call { relative: None }); - reg(x.operands[0], "r8"); - let x = one(&[0xff, 0x25, 0, 0, 0, 0]); - assert_eq!(x.flow, Flow::Jump { relative: None }); - assert_eq!(one(&[0xc3]).flow, Flow::Return); - assert_eq!(one(&[0xcc]).flow, Flow::Trap); - assert_eq!(one(&[0x0f, 5]).flow, Flow::Syscall); - assert_eq!(one(&[0xeb, 0xfe]).relative_target(0x1000), Some(0x1000)); - assert_eq!(one(&[0xeb, 0xfc]).relative_target(0), None); - } - - #[test] - fn scalar_sse_uses_mandatory_prefixes_xmm_registers_and_scalar_memory_width() { - for (prefix, precision) in [(0xf3, 32), (0xf2, 64)] { - for (opcode, mnemonic) in - [(0x10, "mov"), (0x58, "add"), (0x5c, "sub"), (0x59, "mul"), (0x5e, "div")] - { - let suffix = if precision == 32 { "ss" } else { "sd" }; - let x = one(&[prefix, 0x45, 0x0f, opcode, 0xca]); - assert_eq!(x.mnemonic(), format!("{mnemonic}{suffix}")); - reg(x.operands[0], "xmm9"); - reg(x.operands[1], "xmm10"); - let x = one(&[prefix, 0x47, 0x0f, opcode, 0x4c, 0xcc, 0x80]); - reg(x.operands[0], "xmm9"); - let Operand::Memory(m) = x.operands[1] else { panic!() }; - assert_eq!(m.width, precision); - assert_eq!(m.base.unwrap().name(), "r12"); - assert_eq!(m.index.unwrap().name(), "r9"); - } - let x = one(&[prefix, 0x45, 0x0f, 0x11, 0x7d, 8]); - let Operand::Memory(m) = x.operands[0] else { panic!() }; - assert_eq!(m.width, precision); - reg(x.operands[1], "xmm15"); - } - for bytes in [ - &[0x0f, 0x10, 0xc0][..], - &[0x66, 0x0f, 0x58, 0xc0][..], - &[0xf3, 0x90][..], - &[0xc5, 0xfa, 0x10, 0xc0][..], - ] { - assert!(matches!(decode(bytes, 0), Err(DecodeError::Unsupported { .. }))); - } - } - - #[test] - fn every_integer_encoder_family_and_width_decodes_without_a_rust_fallback() { - let mut cases = vec![ - "ret".into(), - "nop".into(), - "syscall".into(), - "int3".into(), - "cwd".into(), - "cdq".into(), - "cqo".into(), - "push -1".into(), - "push 128".into(), - "push r8".into(), - "pop r15w".into(), - "call rax".into(), - "jmp qword [r12+r9*8+128]".into(), - "lea r9,[r12+r13*4-129]".into(), - ]; - for (a, b, width) in [ - ("al", "cl", 8), - ("ax", "cx", 16), - ("eax", "ecx", 32), - ("rax", "rcx", 64), - ("r8b", "r9b", 8), - ("r8w", "r9w", 16), - ("r8d", "r9d", 32), - ("r8", "r9", 64), - ] { - let size = match width { - 8 => "byte", - 16 => "word", - 32 => "dword", - _ => "qword", - }; - for mnemonic in ["mov", "add", "sub", "and", "or", "xor", "cmp"] { - cases.push(format!("{mnemonic} {a},{b}")); - cases.push(format!("{mnemonic} {a},127")); - cases.push(format!("{mnemonic} {a},128")); - cases.push(format!("{mnemonic} {a},{size} [r12+r9*8-128]")); - cases.push(format!("{mnemonic} {size} [r13+128],{a}")); - cases.push(format!("{mnemonic} {size} [r13],1")); - } - for mnemonic in ["adc", "sbb", "test"] { - cases.push(format!("{mnemonic} {a},{b}")); - } - for mnemonic in ["not", "neg", "div", "idiv"] { - cases.push(format!("{mnemonic} {a}")); - } - for mnemonic in ["shl", "sal", "shr", "sar"] { - for count in ["1", "cl", "255"] { - cases.push(format!("{mnemonic} {a},{count}")); - } - } - if width != 8 { - cases.push(format!("imul {a},{b}")); - cases.push(format!("imul {a},{b},-1")); - cases.push(format!("imul {a},{b},128")); - cases.push(format!("imul {a},{size} [r12+8]")); - for condition in [ - "o", "no", "b", "ae", "e", "ne", "be", "a", "s", "ns", "p", "np", "l", "ge", - "le", "g", - ] { - cases.push(format!("cmov{condition} {a},{b}")); - } - for mnemonic in ["movzx", "movsx"] { - cases.push(format!("{mnemonic} {a},byte [r12]")); - } - } - } - for condition in - ["o", "no", "b", "ae", "e", "ne", "be", "a", "s", "ns", "p", "np", "l", "ge", "le", "g"] - { - cases.push(format!("set{condition} r9b")); - cases.push(format!("set{condition} byte [r12+127]")); - } - cases.extend([ - "movsxd r8,r9d".into(), - "movsx r8d,word [r9]".into(), - "movzx r8,word [r12]".into(), - "mov ah,cl".into(), - "mov spl,al".into(), - ]); - for source in cases { - let bytes = encoded(&source); - let instruction = one(&bytes); - let first = source.split_whitespace().next().unwrap(); - let expected = if first == "sal" { "shl" } else { first }; - assert_eq!(instruction.mnemonic(), expected, "{source}"); - for n in 0..bytes.len() { - assert!( - matches!(decode(&bytes[..n], 0), Err(DecodeError::Truncated { .. })), - "{source} truncated{n}: {:?}", - decode(&bytes[..n], 0) - ); - } - } - for source in ["jmp done\ndone:", "call done\ndone:", "je done\ndone:", "loop done\ndone:"] - { - one(&encoded(source)); - } - } - - #[test] - fn every_sib_base_index_scale_and_displacement_boundary_is_bounded() { - let names = [ - "rax", "rcx", "rdx", "rbx", "rsp", "rbp", "rsi", "rdi", "r8", "r9", "r10", "r11", - "r12", "r13", "r14", "r15", - ]; - for base in names { - for index in names { - if index == "rsp" { - continue; - } - for scale in [1, 2, 4, 8] { - for displacement in [-129, -128, 0, 127, 128] { - let source = format!("mov rax,[{base}+{index}*{scale}{displacement:+}]"); - let instruction = one(&encoded(&source)); - let Operand::Memory(m) = instruction.operands[1] else { panic!() }; - assert_eq!(m.base.unwrap().name(), base, "{source}"); - assert_eq!(m.index.unwrap().name(), index, "{source}"); - assert_eq!((m.scale, m.displacement), (scale, displacement)); - } - } - } - } - } - - #[test] - fn statuses_prefix_order_offset_and_fifteen_byte_limit_are_explicit() { - assert!(matches!(decode(&[0x8d, 0xc0], 0), Err(DecodeError::Invalid { .. }))); - assert!(matches!(decode(&[0x67, 0x90], 0), Err(DecodeError::Unsupported { .. }))); - assert!(matches!(decode(&[0x41, 0x90], 0), Err(DecodeError::Unsupported { .. }))); - assert!(matches!(decode(&[0xf3, 0x90], 0), Err(DecodeError::Unsupported { .. }))); - assert!(matches!(decode(&[0x90], 2), Err(DecodeError::Invalid { .. }))); - assert!(matches!(decode(&[0x90], 1), Err(DecodeError::Truncated { .. }))); - let mut longest = vec![0x66; 14]; - longest.push(0x90); - one(&longest); - longest.insert(0, 0x66); - assert!(matches!(decode(&longest, 0), Err(DecodeError::Overlong { .. }))); - assert!(matches!(decode(&[0x66; 15], 0), Err(DecodeError::Overlong { .. }))); - let x = decode(&[0xcc, 0x48, 0x89, 0xd8, 0xc3], 1).unwrap(); - assert_eq!(x.offset, 1); - assert_eq!(x.original_bytes(), [0x48, 0x89, 0xd8]); - } - - #[test] - fn raw_abi_capacity_version_and_every_failed_decode_leave_output_unchanged() { - extern "C" { - fn whale_wave_reverse_decode( - abi: u64, - data: *const u8, - len: u64, - offset: u64, - output: *mut u64, - capacity: u64, - ) -> i32; - } - for (bytes, abi, offset, cap, expected) in [ - (vec![0x90], 0, 0, 96, 6), - (vec![0x90], 1, 0, 95, 5), - (vec![0x90], 1, 2, 96, 1), - (vec![0x0f], 1, 0, 96, 2), - (vec![0xc5], 1, 0, 96, 3), - (vec![0x66; 15], 1, 0, 96, 4), - (vec![0x8d, 0xc0], 1, 0, 96, 1), - ] { - let mut output = [u64::MAX; 96]; - // SAFETY: live, aligned caller-owned buffers; invalid scalar arguments - // exercise the ABI's documented rejection-before-publication path. - let status = unsafe { - whale_wave_reverse_decode( - abi, - bytes.as_ptr(), - bytes.len() as u64, - offset, - output.as_mut_ptr(), - cap, - ) - }; - assert_eq!(status, expected); - assert_eq!(output, [u64::MAX; 96]); - } - let input = [0x90u8]; - let mut output = [u64::MAX; 96]; - // SAFETY: null and oversized scalar arguments must be rejected before - // any pointer arithmetic/access; the sentinel output is valid. - unsafe { - assert_eq!( - whale_wave_reverse_decode(1, std::ptr::null(), 0, 0, output.as_mut_ptr(), 96), - 1 - ); - assert_eq!( - whale_wave_reverse_decode(1, input.as_ptr(), 1, 0, std::ptr::null_mut(), 96), - 1 - ); - assert_eq!( - whale_wave_reverse_decode(1, input.as_ptr(), u64::MAX, 0, output.as_mut_ptr(), 96), - 1 - ); - } - assert_eq!(output, [u64::MAX; 96]); - } - - #[cfg(target_os = "linux")] - #[test] - fn actual_kernel_reads_never_cross_a_protected_input_boundary() { - use std::ffi::c_void; - - extern "C" { - fn mmap( - address: *mut c_void, - length: usize, - protection: i32, - flags: i32, - fd: i32, - offset: i64, - ) -> *mut c_void; - - fn mprotect(address: *mut c_void, length: usize, protection: i32) -> i32; - - fn munmap(address: *mut c_void, length: usize) -> i32; - - fn sysconf(name: i32) -> i64; - - fn whale_wave_reverse_decode( - abi: u64, - data: *const u8, - len: u64, - offset: u64, - output: *mut u64, - capacity: u64, - ) -> i32; - } - // SAFETY: one private mapping is retained until all calls finish. Every - // input ends at the protected page, including zero-length input. - unsafe { - let page = usize::try_from(sysconf(30)).unwrap(); - assert!(page > 0); - let mapping = mmap(std::ptr::null_mut(), page * 2, 3, 0x22, -1, 0); - assert_ne!(mapping as isize, -1); - assert_eq!(mprotect(mapping.cast::().add(page).cast(), page, 0), 0); - let mut random = 0x12345678u32; - for length in 0..=31 { - for _ in 0..100 { - let data = mapping.cast::().add(page - length); - for i in 0..length { - random = random.wrapping_mul(1664525).wrapping_add(1013904223); - data.add(i).write((random >> 24) as u8); - } - let mut output = [u64::MAX; 96]; - let status = whale_wave_reverse_decode( - 1, - data, - length as u64, - 0, - output.as_mut_ptr(), - 96, - ); - assert!((0..=4).contains(&status)); - if status == 0 { - assert!(output[2] > 0 && output[2] <= 15 && output[2] <= length as u64); - } else { - assert_eq!(output, [u64::MAX; 96]); - } - } - } - assert_eq!(munmap(mapping, page * 2), 0); - } + assert!(!backend_available()); + assert_eq!(backend_name(), "unavailable"); + for (bytes, offset) in [(&[0x90][..], 0), (&[][..], 0), (&[0xc3][..], usize::MAX)] { + assert_eq!(decode(bytes, offset), Err(DecodeError::CoreUnavailable)); } } diff --git a/reverse/tests/presentation.rs b/reverse/tests/presentation.rs new file mode 100644 index 0000000..c4c0c12 --- /dev/null +++ b/reverse/tests/presentation.rs @@ -0,0 +1,78 @@ +// SPDX-License-Identifier: MPL-2.0 +//! Rendering caller-supplied typed facts does not require a decoder backend. +use reverse::*; + +fn call() -> Instruction { + let mut bytes = [0; 15]; + bytes[..5].copy_from_slice(&[0xe8, 0, 0, 0, 0]); + Instruction { + offset: 0, + length: 5, + bytes, + opcode: Opcode::Call, + condition: None, + operands: vec![Operand::Relative(Relative { displacement: 0, encoded_width: 32 })], + encoding: Encoding { + prefixes: vec![], + rex: None, + opcode_offset: 0, + opcode_len: 1, + modrm: None, + sib: None, + displacement: None, + immediate: Some(EncodingField { offset: 1, width: 4, bits: 0 }), + }, + flow: Flow::Call { relative: Some(0) }, + } +} + +#[test] +fn symbolic_relocations_suppress_placeholder_call_targets() { + let instruction = call(); + let annotation = image::Annotation { + region: 0, + offset: 1, + width: 4, + symbol: "external".into(), + addend: -4, + kind: object::RelocKind::PLT32, + }; + let annotations = [&annotation]; + let report = format::instruction_json(&instruction, 0x400000, &annotations); + assert!(report["target"].is_null()); + assert_eq!(report["relocations"][0]["symbol"], "external"); + assert_eq!(report["encoding"]["immediate"]["width_bytes"], 4); + let text = format::instruction_text(&instruction, 0x400000, &annotations); + assert!(text.contains("call reloc(external-4)"), "{text}"); + assert!(!text.contains("call 0x400005")); +} + +#[test] +fn checked_target_and_address_rendering_preserves_overflow() { + let mut instruction = call(); + assert_eq!(instruction.relative_target(0x1000), Some(0x1005)); + assert_eq!(instruction.relative_target(u64::MAX), None); + instruction.offset = 1; + let report = format::instruction_json(&instruction, u64::MAX, &[]); + assert!(report["address"].is_null()); + assert!(report["target"].is_null()); + assert!(format::instruction_text(&instruction, u64::MAX, &[]).starts_with("overflow")); + assert_eq!(instruction.original_bytes(), [0xe8, 0, 0, 0, 0]); +} + +#[test] +fn register_and_immediate_widths_are_presentation_facts() { + for (index, width, high8, name) in [ + (0, 8, true, "ah"), + (4, 8, false, "spl"), + (9, 16, false, "r9w"), + (15, 32, false, "r15d"), + (8, 64, false, "r8"), + ] { + let register = Register { class: RegisterClass::General, index, width, high8 }; + assert_eq!(register.name(), name); + } + let immediate = Immediate { value: 0xff, width: 64, encoded_width: 8, sign_extended: true }; + assert_eq!(immediate.signed_value(), -1); + assert_eq!(format::operand_text(&Operand::Immediate(immediate), &call(), 0), "-1"); +} diff --git a/reverse/tests/roundtrip.rs b/reverse/tests/roundtrip.rs deleted file mode 100644 index c644321..0000000 --- a/reverse/tests/roundtrip.rs +++ /dev/null @@ -1,68 +0,0 @@ -//! The documented canonical subset is tested through the actual Wave decoder. -#[cfg(whale_wave_reverse)] -mod native { - use amd64::AMD64; - - use assembler::assemble; - - #[test] - fn canonical_operand_text_reassembles_the_documented_subset_exactly() { - // These are current Whale encoder outputs with no redundant prefixes, - // symbolic fields, relative targets or alternative forced encodings. - // The test does not use the retained raw bytes as assembly input. - for source in [ - "mov rax,r9", - "mov ah,bl", - "mov spl,al", - "mov r9w,0x1234", - "mov eax,0x12345678", - "mov r8,0x123456789abcdef", - "add rax,r9", - "sub r8,-1", - "xor eax,ecx", - "cmp r10,127", - "test rax,r9", - "not r9", - "neg r8d", - "imul r9,r10,-7", - "shl rax,1", - "shr r9,cl", - "sar eax,7", - "mov rax,qword [r12+r9*8-128]", - "mov dword [rbp+128],r9d", - "movzx r9d,byte [r12+8]", - "movss xmm9,xmm10", - "movsd xmm15,xmm8", - "movss xmm9,dword [r12+r9*4-128]", - "movsd qword [rbp+128],xmm15", - "addss xmm9,xmm10", - "subsd xmm15,qword [r12+8]", - "mulss xmm0,dword [rbp-8]", - "divsd xmm8,xmm9", - "nop", - "ret", - ] { - let original = assemble(source, &AMD64) - .unwrap_or_else(|error| panic!("fixture {source:?}: {error}")) - .sections - .remove(0) - .data; - let decoded = reverse::decode(&original, 0) - .unwrap_or_else(|error| panic!("decode {source:?}: {error}")); - assert_eq!(usize::from(decoded.length), original.len(), "{source}"); - let operands = decoded - .operands - .iter() - .map(|operand| reverse::format::operand_text(operand, &decoded, 0)) - .collect::>() - .join(", "); - let rendered = format!("{} {operands}\n", decoded.mnemonic()); - let reassembled = assemble(&rendered, &AMD64) - .unwrap_or_else(|error| panic!("rendered {source:?} as {rendered:?}: {error}")) - .sections - .remove(0) - .data; - assert_eq!(reassembled, original, "{source:?} rendered as {rendered:?}"); - } - } -} diff --git a/reverse/wave/amd64.wave b/reverse/wave/amd64.wave deleted file mode 100644 index 7130c1b..0000000 --- a/reverse/wave/amd64.wave +++ /dev/null @@ -1,598 +0,0 @@ -// SPDX-License-Identifier: MPL-2.0 -// AMD64 whitelist decoder ABI 1. No allocator, imports, OS calls or source recovery. -// Output is 96 u64 words, committed only after complete successful decoding. -// Status: 0 success, 1 invalid argument/encoding, 2 truncated, 3 unsupported, -// 4 overlong, 5 output capacity, 6 ABI mismatch. All offsets are byte-relative. -struct DecodeState { - data: ptr; - remaining: u64; - position: u64; - status: i32; - output: ptr; - rex: u64; -} - -fun reverse_read(state: ptr, count: u64) -> u64 { - if (state.status != 0) { - return 0; - } - if (count > 15 - state.position) { - state.status = 4; - return 0; - } - if (count > state.remaining - state.position) { - state.status = 2; - return 0; - } - var value: u64 = 0; - var i: u64 = 0; - while (i < count) { - value = value | ((state.data[state.position + i] as u64) << (i * 8)); - i += 1; - } - state.position += count; - return value; -} - -fun reverse_field(state: ptr, slot: u64, count: u64) -> u64 { - state.output[slot] = state.position + 1; - state.output[slot + 1] = count; - var value: u64 = reverse_read(state, count); - state.output[slot + 2] = value; - return value; -} - -fun reverse_signed(value: u64, count: u64) -> u64 { - if (count == 1) { - return (value as i8) as i64 as u64; - } - if (count == 2) { - return (value as i16) as i64 as u64; - } - if (count == 4) { - return (value as i32) as i64 as u64; - } - return value; -} - -fun reverse_register(output: ptr, operand: u64, width: u64, code: u64, - rex: u64, register_kind: u64) { - var at: u64 = 40 + operand * 16; - output[at] = register_kind; - output[at + 1] = width; - output[at + 2] = code; - if (register_kind == 1 && width == 8 && code >= 4 && code <= 7 && rex == 0) { - output[at + 2] = code - 4; - output[at + 3] = 1; - } -} - -fun reverse_rm(state: ptr, operand: u64, width: u64, - register_kind: u64, modrm: u64) { - var mode: u64 = modrm >> 6; - var rm: u64 = modrm & 7; - var record_out: ptr = state.output; - if (mode == 3) { - var register_width: u64 = width; - if (register_kind == 2) { - register_width = 128; - } - reverse_register(record_out, operand, register_width, rm + ((state.rex & 1) << 3), state.rex, register_kind); - return; - } - var at: u64 = 40 + operand * 16; - record_out[at] = 3; - record_out[at + 1] = width; - record_out[at + 4] = 1; - var displacement_bytes: u64 = 0; - if (rm == 4) { - record_out[12] = state.position + 1; - var sib: u64 = reverse_read(state, 1); - record_out[13] = sib; - record_out[at + 4] = (1 as u64) << (sib >> 6); - var index: u64 = (sib >> 3) & 7; - if (index != 4 || (state.rex & 2) != 0) { - record_out[at + 3] = index + ((state.rex & 2) << 2) + 1; - } - var base: u64 = sib & 7; - if (mode == 0 && base == 5) { - // SIB base=5 in mode0 has no base even with REX.B; disp32 is signed. - displacement_bytes = 4; - } else { - record_out[at + 2] = base + ((state.rex & 1) << 3) + 1; - } - } else if (mode == 0 && rm == 5) { - // RIP-relative is independent of REX.B. Address-size override is unsupported. - record_out[at + 2] = 17; - displacement_bytes = 4; - } else { - record_out[at + 2] = rm + ((state.rex & 1) << 3) + 1; - } - if (mode == 1) { - displacement_bytes = 1; - } else if (mode == 2) { - displacement_bytes = 4; - } - if (displacement_bytes != 0) { - var displacement: u64 = reverse_field(state, 14, displacement_bytes); - record_out[at + 5] = reverse_signed(displacement, displacement_bytes); - } -} - -fun reverse_decode_body(state: ptr) -> i32 { - var record_out: ptr = state.output; - var operand16: bool = false; - var mandatory: u64 = 0; - var prefixes: u64 = 0; - var first: u64 = 0; - while (true) { - first = reverse_read(state, 1); - if (state.status != 0) { - return state.status; - } - if (first == 102 || first == 242 || first == 243) { - // A legacy prefix after a REX invalidates that earlier REX. - state.rex = 0; - if (first == 102) { - operand16 = true; - } else { - mandatory = first; - } - } else if (first >= 64 && first <= 79) { - state.rex = first; - } else if (first == 103 || first == 240 || first == 38 || first == 46 - || first == 54 || first == 62 || first == 100 || first == 101) { - return 3; - } else { - break; - } - record_out[24 + prefixes] = first; - prefixes += 1; - if (prefixes >= 15) { - return 4; - } - } - record_out[7] = prefixes; - record_out[8] = state.position - 1; - record_out[9] = 1; - record_out[20] = state.rex; - var width: u64 = 32; - if (operand16) { - width = 16; - } - if ((state.rex & 8) != 0) { - width = 64; - } - var format: u64 = 0; - var opcode: u64 = 0; - var source_width: u64 = width; - var immediate_bytes: u64 = 0; - var sign_extended: u64 = 0; - var group: u64 = 0; - var shift_kind: u64 = 0; - var sse: bool = false; - var condition: u64 = 16; - var flow: u64 = 0; - var opcode_register: u64 = first & 7; - if (first <= 59 && (first & 7) <= 3) { - var operations: array = [2, 3, 4, 5, 6, 7, 8, 9]; - opcode = operations[first >> 3]; - if ((first & 1) == 0) { - width = 8; - } - format = 1; - if ((first & 2) != 0) { - format = 2; - } - } else if (first >= 136 && first <= 139) { - opcode = 1; - format = 1; - if ((first & 1) == 0) { - width = 8; - } - if ((first & 2) != 0) { - format = 2; - } - } else if (first == 128 || first == 129 || first == 131) { - format = 3; - group = 1; - if (first == 128) { - width = 8; - } - immediate_bytes = 1; - if (first == 129) { - immediate_bytes = 4; - if (width == 16) { - immediate_bytes = 2; - } - } - if ((first == 131 && width > 8) || width == 64) { - sign_extended = 1; - } - } else if (first == 198 || first == 199) { - opcode = 1; - format = 3; - group = 2; - if (first == 198) { - width = 8; - } - immediate_bytes = width / 8; - if (width == 64) { - immediate_bytes = 4; - sign_extended = 1; - } - } else if (first >= 176 && first <= 191) { - opcode = 1; - format = 4; - if (first < 184) { - width = 8; - } - immediate_bytes = width / 8; - } else if (first >= 80 && first <= 95) { - opcode = 11; - if (first >= 88) { - opcode = 12; - } - width = 64; - if (operand16 && (state.rex & 8) == 0) { - width = 16; - } - format = 6; - } else if (first == 104 || first == 106) { - opcode = 11; - format = 13; - width = 64; - immediate_bytes = 4; - if (operand16 && (state.rex & 8) == 0) { - width = 16; - immediate_bytes = 2; - } - if (first == 106) { - immediate_bytes = 1; - } - if (immediate_bytes * 8 < width) { - sign_extended = 1; - } - } else if (first == 232 || first == 233 || first == 235 || first == 226 - || (first >= 112 && first <= 127)) { - opcode = 13; - flow = 3; - format = 5; - immediate_bytes = 1; - if (first == 232 || first == 233) { - immediate_bytes = 4; - } - if (first == 232) { - opcode = 16; - flow = 1; - } else if (first == 226) { - opcode = 15; - flow = 6; - } else if (first >= 112 && first <= 127) { - opcode = 14; - condition = first & 15; - flow = 5; - } - } else if (first == 195) { - opcode = 17; - flow = 7; - } else if (first == 144) { - if ((state.rex & 1) != 0) { - return 3; - } - opcode = 18; - } else if (first == 204) { - opcode = 20; - flow = 8; - } else if (first == 153) { - opcode = 31; - if (width == 16) { - opcode = 30; - } else if (width == 64) { - opcode = 32; - } - } else if (first == 141) { - opcode = 21; - format = 2; - } else if (first == 132 || first == 133) { - opcode = 22; - format = 1; - if (first == 132) { - width = 8; - } - } else if (first == 246 || first == 247) { - format = 7; - group = 3; - if (first == 246) { - width = 8; - } - } else if (first == 192 || first == 193 || (first >= 208 && first <= 211)) { - format = 8; - group = 4; - if ((first & 1) == 0) { - width = 8; - } - if (first == 192 || first == 193) { - shift_kind = 1; - immediate_bytes = 1; - } else if (first == 210 || first == 211) { - shift_kind = 2; - } - } else if (first == 105 || first == 107) { - opcode = 10; - format = 9; - immediate_bytes = 4; - if (width == 16) { - immediate_bytes = 2; - } - if (first == 107) { - immediate_bytes = 1; - } - if (immediate_bytes * 8 < width) { - sign_extended = 1; - } - } else if (first == 99) { - if (width != 64) { - return 3; - } - opcode = 35; - format = 12; - source_width = 32; - } else if (first == 255) { - format = 7; - group = 5; - width = 64; - if (operand16) { - return 3; - } - } else if (first == 15) { - var second: u64 = reverse_read(state, 1); - if (state.status != 0) { - return state.status; - } - record_out[9] = 2; - if (second == 5) { - opcode = 19; - flow = 9; - } else if (second >= 128 && second <= 143) { - opcode = 14; - condition = second & 15; - flow = 5; - format = 5; - immediate_bytes = 4; - } else if (second >= 144 && second <= 159) { - opcode = 36; - condition = second & 15; - width = 8; - format = 14; - } else if (second >= 64 && second <= 79) { - opcode = 37; - condition = second & 15; - format = 2; - } else if (second == 175) { - opcode = 10; - format = 2; - } else if (second == 182 || second == 183 || second == 190 || second == 191) { - opcode = 33; - if (second >= 190) { - opcode = 34; - } - source_width = 8; - if ((second & 1) != 0) { - source_width = 16; - } - if (width <= source_width) { - return 3; - } - format = 12; - } else if (second == 16 || second == 17 || second == 88 || second == 89 - || second == 92 || second == 94) { - if ((mandatory != 242 && mandatory != 243) || operand16) { - return 3; - } - sse = true; - var precision: u64 = 0; - width = 32; - if (mandatory == 242) { - precision = 1; - width = 64; - } - opcode = 38 + precision; - if (second == 88) { - opcode = 40 + precision; - } else if (second == 92) { - opcode = 42 + precision; - } else if (second == 89) { - opcode = 44 + precision; - } else if (second == 94) { - opcode = 46 + precision; - } - format = 10; - if (second == 17) { - format = 11; - } - } else { - return 3; - } - } else { - return 3; - } - if (mandatory != 0 && !sse) { - return 3; - } - var modrm: u64 = 0; - if (format == 1 || format == 2 || format == 3 || format == 7 || format == 8 - || format == 9 || format == 10 || format == 11 || format == 12 || format == 14) { - record_out[10] = state.position + 1; - modrm = reverse_read(state, 1); - if (state.status != 0) { - return state.status; - } - record_out[11] = modrm; - var extension: u64 = (modrm >> 3) & 7; - if (group == 1) { - var operations: array = [2, 3, 4, 5, 6, 7, 8, 9]; - opcode = operations[extension]; - } else if (group == 2) { - if (extension != 0) { - return 3; - } - } else if (group == 3) { - if (extension == 2) { - opcode = 23; - } else if (extension == 3) { - opcode = 24; - } else if (extension == 6) { - opcode = 25; - } else if (extension == 7) { - opcode = 26; - } else { - return 3; - } - } else if (group == 4) { - if (extension == 4) { - opcode = 27; - } else if (extension == 5) { - opcode = 28; - } else if (extension == 7) { - opcode = 29; - } else { - return 3; - } - } else if (group == 5) { - if (extension == 2) { - opcode = 16; - flow = 2; - } else if (extension == 4) { - opcode = 13; - flow = 4; - } else { - return 3; - } - } - if (opcode == 21 && modrm >= 192) { - return 1; - } - } - var register_code: u64 = ((modrm >> 3) & 7) + ((state.rex & 4) << 1); - if (format == 1) { - reverse_rm(state, 0, width, 1, modrm); - reverse_register(record_out, 1, width, register_code, state.rex, 1); - record_out[5] = 2; - } else if (format == 2) { - reverse_register(record_out, 0, width, register_code, state.rex, 1); - reverse_rm(state, 1, width, 1, modrm); - record_out[5] = 2; - } else if (format == 3) { - reverse_rm(state, 0, width, 1, modrm); - record_out[5] = 2; - } else if (format == 4 || format == 6) { - reverse_register(record_out, 0, width, opcode_register + ((state.rex & 1) << 3), state.rex, 1); - record_out[5] = 1; - if (format == 4) { - record_out[5] = 2; - } - } else if (format == 5) { - record_out[40] = 5; - record_out[41] = immediate_bytes * 8; - var relative: u64 = reverse_field(state, 17, immediate_bytes); - record_out[42] = reverse_signed(relative, immediate_bytes); - record_out[46] = immediate_bytes * 8; - immediate_bytes = 0; - record_out[5] = 1; - } else if (format == 7 || format == 14) { - reverse_rm(state, 0, width, 1, modrm); - record_out[5] = 1; - } else if (format == 8) { - reverse_rm(state, 0, width, 1, modrm); - record_out[5] = 2; - if (shift_kind == 0) { - record_out[56] = 4; - record_out[57] = 8; - record_out[58] = 1; - } else if (shift_kind == 2) { - reverse_register(record_out, 1, 8, 1, state.rex, 1); - } - } else if (format == 9) { - reverse_register(record_out, 0, width, register_code, state.rex, 1); - reverse_rm(state, 1, width, 1, modrm); - record_out[5] = 3; - } else if (format == 10) { - reverse_register(record_out, 0, 128, register_code, state.rex, 2); - reverse_rm(state, 1, width, 2, modrm); - record_out[5] = 2; - } else if (format == 11) { - reverse_rm(state, 0, width, 2, modrm); - reverse_register(record_out, 1, 128, register_code, state.rex, 2); - record_out[5] = 2; - } else if (format == 12) { - reverse_register(record_out, 0, width, register_code, state.rex, 1); - reverse_rm(state, 1, source_width, 1, modrm); - record_out[5] = 2; - } else if (format == 13) { - record_out[5] = 1; - } - if (immediate_bytes != 0) { - var operand: u64 = record_out[5] - 1; - var at: u64 = 40 + operand * 16; - record_out[at] = 4; - record_out[at + 1] = width; - if (format == 8) { - record_out[at + 1] = 8; - } - record_out[at + 2] = reverse_field(state, 17, immediate_bytes); - record_out[at + 3] = sign_extended; - record_out[at + 6] = immediate_bytes * 8; - } - if (state.status != 0) { - return state.status; - } - record_out[0] = 1; - record_out[1] = 96; - record_out[2] = state.position; - record_out[3] = opcode; - record_out[4] = condition; - record_out[6] = flow; - return 0; -} - -export(c) fun whale_wave_reverse_abi() -> u64 { - return 1; -} - -export(c) fun whale_wave_reverse_decode(abi: u64, data: ptr, length: u64, - offset: u64, output: ptr, capacity: u64) -> i32 { - if (abi != 1) { - return 6; - } - if (data == null || output == null || offset > length || length > 9223372036854775807) { - return 1; - } - if (capacity < 96) { - return 5; - } - var record: array; - var i: u64 = 0; - while (i < 96) { - record[i] = 0; - i += 1; - } - var state: DecodeState = DecodeState { - data: data + offset, - remaining: length - offset, - position: 0, - status: 0, - output: &record[0], - rex: 0 - }; - var status: i32 = reverse_decode_body(&state); - if (status != 0) { - return status; - } - i = 0; - while (i < 96) { - output[i] = record[i]; - i += 1; - } - return 0; -} diff --git a/reverse/wave/cfg.wave b/reverse/wave/cfg.wave deleted file mode 100644 index 4df0c6b..0000000 --- a/reverse/wave/cfg.wave +++ /dev/null @@ -1,521 +0,0 @@ -// SPDX-License-Identifier: MPL-2.0 -// Conservative on-demand CFG and xrefs; traversal and block formation live in Wave. -struct CfgState { - data: ptr; - length: u64; - base: u64; - overlays: ptr; - overlay_count: u64; - owners: ptr; - queue: ptr; - stage: ptr; - instruction_base: u64; - block_base: u64; - edge_base: u64; - stop_base: u64; - max_instructions: u64; - max_blocks: u64; - max_edges: u64; - max_stops: u64; - max_work: u64; - follow_calls: bool; - instructions: u64; - blocks: u64; - edges: u64; - stops: u64; - queued: u64; - work: u64; - status: i32; - target_kind: u64; - target_value: u64; - overlay_used: bool; -} - -fun cfg_charge(state: ptr, amount: u64) { - if (state.status != 0) { - return; - } - if (amount > state.max_work - state.work) { - state.status = 7; - return; - } - state.work += amount; -} - -fun cfg_stop(state: ptr, offset: u64, reason: u64, detail: u64) { - if (state.status != 0) { - return; - } - if (state.stops >= state.max_stops) { - state.status = 11; - return; - } - cfg_charge(state, 1); - if (state.status != 0) { - return; - } - var at: u64 = state.stop_base + state.stops * 4; - state.stage[at] = offset; - state.stage[at + 1] = reason; - state.stage[at + 2] = detail; - state.stage[at + 3] = 0; - state.stops += 1; -} - -fun cfg_edge(state: ptr, from: u64, kind: u64, target_kind: u64, target: u64) { - if (state.status != 0) { - return; - } - if (state.edges >= state.max_edges) { - state.status = 10; - return; - } - cfg_charge(state, 1); - if (state.status != 0) { - return; - } - var at: u64 = state.edge_base + state.edges * 6; - state.stage[at] = from; - state.stage[at + 1] = kind; - state.stage[at + 2] = target_kind; - state.stage[at + 3] = target; - state.stage[at + 4] = 0; - state.stage[at + 5] = 0; - state.edges += 1; -} - -fun cfg_enqueue(state: ptr, address: u64) { - if (state.status != 0 || address < state.base) { - return; - } - var offset: u64 = address - state.base; - if (offset >= state.length) { - return; - } - var leader: u64 = 9223372036854775808; - if ((state.owners[offset] & leader) != 0) { - return; - } - if (state.queued >= state.max_blocks) { - state.status = 9; - return; - } - cfg_charge(state, 1); - if (state.status != 0) { - return; - } - state.owners[offset] = state.owners[offset] | leader; - state.queue[state.queued] = offset; - state.queued += 1; -} - -fun cfg_relative(state: ptr, next: u64, displacement: u64) { - var target: i128 = (state.base as i128) + (next as i128) - + ((displacement as i64) as i128); - state.target_kind = 0; - state.target_value = 0; - if (target >= 0 && target <= 18446744073709551615) { - state.target_kind = 1; - state.target_value = target as u64; - } -} - -// Sorted, disjoint relocation field records: offset,width,target_kind,target. -// A partial/intersecting field never leaves a placeholder-derived numeric target. -fun cfg_overlay(state: ptr, offset: u64, width: u64) { - state.overlay_used = false; - var left: u64 = 0; - var right: u64 = state.overlay_count; - while (left < right && state.status == 0) { - cfg_charge(state, 1); - var middle: u64 = left + (right - left) / 2; - if (state.overlays[middle * 4] < offset) { - left = middle + 1; - } else { - right = middle; - } - } - var candidate: u64 = left; - if (left > 0) { - var previous: u64 = (left - 1) * 4; - if (state.overlays[previous] + state.overlays[previous + 1] > offset) { - candidate = left - 1; - } - } - if (candidate < state.overlay_count) { - var at: u64 = candidate * 4; - if (state.overlays[at] < offset + width - && state.overlays[at] + state.overlays[at + 1] > offset) { - state.overlay_used = true; - state.target_kind = 0; - state.target_value = 0; - if (state.overlays[at] == offset && state.overlays[at + 1] == width) { - state.target_kind = state.overlays[at + 2]; - state.target_value = state.overlays[at + 3]; - } - } - } -} - -fun cfg_references(state: ptr, offset: u64, next: u64, record: ptr) { - var operand: u64 = 0; - while (operand < record[5] && state.status == 0) { - cfg_charge(state, 1); - var at: u64 = 40 + operand * 16; - if (record[at] == 3 && record[14] != 0) { - var static_address: bool = false; - if (record[at + 2] == 17) { - cfg_relative(state, next, record[at + 5]); - static_address = true; - } else if (record[at + 2] == 0 && record[at + 3] == 0) { - state.target_kind = 1; - state.target_value = record[at + 5]; - static_address = true; - } - if (!static_address) { - state.target_kind = 0; - state.target_value = 0; - } - cfg_overlay(state, offset + record[14] - 1, record[15]); - if (static_address || state.overlay_used) { - var kind: u64 = 10; - if (record[3] == 21) { - kind = 11; - } - cfg_edge(state, offset, kind, state.target_kind, state.target_value); - } - } else if (record[at] == 4 && record[17] != 0) { - state.target_kind = 0; - state.target_value = 0; - cfg_overlay(state, offset + record[17] - 1, record[18]); - if (state.overlay_used) { - cfg_edge(state, offset, 11, state.target_kind, state.target_value); - } - } - operand += 1; - } -} - -fun cfg_block(state: ptr, start: u64, end: u64, first: u64, count: u64, - last: u64) { - if (state.status != 0 || count == 0) { - return; - } - if (state.blocks >= state.max_blocks) { - state.status = 9; - return; - } - cfg_charge(state, 1); - if (state.status != 0) { - return; - } - var at: u64 = state.block_base + state.blocks * 5; - state.stage[at] = start; - state.stage[at + 1] = end; - state.stage[at + 2] = first; - state.stage[at + 3] = count; - state.stage[at + 4] = 0; - state.blocks += 1; - var record: u64 = state.instruction_base + last * 97; - if (state.stage[record + 1 + 6] == 0) { - cfg_edge(state, state.stage[record], 0, 1, state.base + end); - } -} - -fun cfg_run(state: ptr, seeds: ptr, seed_count: u64) { - cfg_charge(state, state.length); - if (state.status != 0) { - return; - } - var i: u64 = 0; - while (i < state.length) { - state.owners[i] = 0; - i += 1; - } - i = 0; - while (i < seed_count && state.status == 0) { - cfg_enqueue(state, state.base + seeds[i]); - i += 1; - } - var queued: u64 = 0; - var mask: u64 = 4611686018427387903; - var leader: u64 = 9223372036854775808; - while (queued < state.queued && state.status == 0) { - var cursor: u64 = state.queue[queued]; - queued += 1; - var first: bool = true; - while (cursor < state.length && state.status == 0) { - cfg_charge(state, 1); - if (state.status != 0) { - return; - } - if (!first && (state.owners[cursor] & leader) != 0) { - break; - } - first = false; - var owner: u64 = state.owners[cursor] & mask; - if (owner != 0) { - var existing: u64 = state.stage[state.instruction_base + (owner - 1) * 97]; - if (existing != cursor) { - cfg_stop(state, cursor, 5, existing); - } - break; - } - if (state.instructions >= state.max_instructions) { - state.status = 8; - return; - } - var at: u64 = state.instruction_base + state.instructions * 97; - var record: ptr = state.stage + at + 1; - var decoded: i32 = whale_wave_reverse_decode(1, state.data, state.length, - cursor, record, 96); - if (decoded != 0) { - cfg_stop(state, cursor, decoded as u64, 0); - break; - } - var length: u64 = record[2]; - var next: u64 = cursor + length; - i = cursor; - var conflict: bool = false; - while (i < next && state.status == 0) { - cfg_charge(state, 1); - owner = state.owners[i] & mask; - if (owner != 0) { - var existing: u64 = state.stage[state.instruction_base + (owner - 1) * 97]; - cfg_stop(state, cursor, 5, existing); - conflict = true; - break; - } - i += 1; - } - if (conflict || state.status != 0) { - break; - } - state.stage[at] = cursor; - i = cursor; - while (i < next && state.status == 0) { - cfg_charge(state, 1); - state.owners[i] = (state.owners[i] & leader) | (state.instructions + 1); - i += 1; - } - state.instructions += 1; - cfg_references(state, cursor, next, record); - var flow: u64 = record[6]; - if (flow == 0) { - cursor = next; - if (cursor == state.length) { - cfg_stop(state, cursor, 6, 0); - } - continue; - } - if (flow == 1 || flow == 3 || flow == 5 || flow == 6) { - cfg_relative(state, next, record[42]); - cfg_overlay(state, cursor + record[17] - 1, record[18]); - var kind: u64 = 2; - if (flow == 1) { - kind = 1; - } else if (flow == 5) { - kind = 3; - } else if (flow == 6) { - kind = 5; - } - cfg_edge(state, cursor, kind, state.target_kind, state.target_value); - if (state.target_kind == 1 && (flow != 1 || state.follow_calls)) { - cfg_enqueue(state, state.target_value); - } - if (state.target_kind == 0 && !state.overlay_used) { - cfg_stop(state, cursor, 9, 0); - } - } else if (flow == 2 || flow == 4) { - var kind: u64 = 7; - if (flow == 4) { - kind = 8; - cfg_stop(state, cursor, 7, 0); - } - cfg_edge(state, cursor, kind, 0, 0); - } else if (flow == 9) { - cfg_edge(state, cursor, 9, 0, 0); - cfg_stop(state, cursor, 8, 0); - } - if (flow == 1 || flow == 2 || flow == 5 || flow == 6) { - var fallthrough: u64 = 0; - if (flow == 5) { - fallthrough = 4; - } else if (flow == 6) { - fallthrough = 6; - } - cfg_edge(state, cursor, fallthrough, 1, state.base + next); - cfg_enqueue(state, state.base + next); - if (next == state.length) { - cfg_stop(state, next, 6, 0); - } - } - break; - } - } - // Address-order block formation splits late/backward leaders without host - // traversal or invented instructions. Every discovered interval is explicit. - var cursor: u64 = 0; - var active: bool = false; - var block_start: u64 = 0; - var block_end: u64 = 0; - var first_instruction: u64 = 0; - var count: u64 = 0; - var last: u64 = 0; - while (cursor < state.length && state.status == 0) { - cfg_charge(state, 1); - var owner: u64 = state.owners[cursor] & mask; - if (owner == 0) { - if (active) { - cfg_block(state, block_start, block_end, first_instruction, count, last); - active = false; - } - cursor += 1; - continue; - } - var index: u64 = owner - 1; - var at: u64 = state.instruction_base + index * 97; - if (state.stage[at] != cursor) { - // An instruction interior cannot become a separate block. - cursor += 1; - continue; - } - if (active && (state.owners[cursor] & leader) != 0) { - cfg_block(state, block_start, block_end, first_instruction, count, last); - active = false; - } - if (!active) { - active = true; - block_start = cursor; - first_instruction = index; - count = 0; - } - count += 1; - last = index; - block_end = cursor + state.stage[at + 1 + 2]; - if (state.stage[at + 1 + 6] != 0) { - cfg_block(state, block_start, block_end, first_instruction, count, last); - active = false; - } - cursor = block_end; - } - if (active && state.status == 0) { - cfg_block(state, block_start, block_end, first_instruction, count, last); - } -} - -export(c) fun whale_wave_reverse_cfg(abi: u64, data: ptr, length: u64, base: u64, - seeds: ptr, seed_count: u64, overlays: ptr, overlay_count: u64, - options: ptr, options_count: u64, workspace: ptr, workspace_words: u64, - output: ptr, output_words: u64) -> i32 { - if (abi != 1) { - return 6; - } - if (data == null || options == null || workspace == null || output == null - || (seed_count != 0 && seeds == null) || (overlay_count != 0 && overlays == null) - || options_count != 6 || length > 16777216 || base > 18446744073709551615 - length) { - return 1; - } - var max_instructions: u64 = options[0]; - var max_blocks: u64 = options[1]; - var max_edges: u64 = options[2]; - var max_stops: u64 = options[3]; - if (max_instructions > 1000000 || max_blocks > 1000000 || max_edges > 4000000 - || max_stops > 1000000 || seed_count > 1000000 || overlay_count > 1000000 - || options[5] > 1) { - return 1; - } - var block_base: u64 = 16 + max_instructions * 97; - var edge_base: u64 = block_base + max_blocks * 5; - var stop_base: u64 = edge_base + max_edges * 6; - var total_words: u64 = stop_base + max_stops * 4; - var stage_base: u64 = length + max_blocks; - if (output_words < total_words || workspace_words < stage_base + total_words) { - return 5; - } - if (seed_count > options[4] || overlay_count > options[4] - seed_count) { - return 7; - } - var i: u64 = 0; - while (i < seed_count) { - if (seeds[i] >= length) { - return 1; - } - i += 1; - } - var previous_end: u64 = 0; - i = 0; - while (i < overlay_count) { - var at: u64 = i * 4; - var offset: u64 = overlays[at]; - var width: u64 = overlays[at + 1]; - if (width == 0 || width > 8 || offset > length || width > length - offset - || offset < previous_end || overlays[at + 2] > 2) { - return 1; - } - previous_end = offset + width; - i += 1; - } - var state: CfgState = CfgState { - data: data, length: length, base: base, overlays: overlays, - overlay_count: overlay_count, owners: workspace, queue: workspace + length, - stage: workspace + stage_base, instruction_base: 16, - block_base: block_base, edge_base: edge_base, stop_base: stop_base, - max_instructions: max_instructions, max_blocks: max_blocks, - max_edges: max_edges, max_stops: max_stops, max_work: options[4], - follow_calls: options[5] == 1, instructions: 0, blocks: 0, edges: 0, - stops: 0, queued: 0, work: 0, status: 0, target_kind: 0, - target_value: 0, overlay_used: false - }; - cfg_charge(&state, seed_count + overlay_count); - cfg_run(&state, seeds, seed_count); - var publish_words: u64 = 16 + state.instructions * 97 + state.blocks * 5 - + state.edges * 6 + state.stops * 4; - cfg_charge(&state, publish_words); - if (state.status != 0) { - return state.status; - } - i = 0; - while (i < 16) { - state.stage[i] = 0; - i += 1; - } - state.stage[0] = 1; - state.stage[1] = total_words; - state.stage[2] = state.instructions; - state.stage[3] = state.blocks; - state.stage[4] = state.edges; - state.stage[5] = state.stops; - state.stage[6] = state.work; - state.stage[8] = 16; - state.stage[9] = block_base; - state.stage[10] = edge_base; - state.stage[11] = stop_base; - i = 0; - while (i < 16) { - output[i] = state.stage[i]; - i += 1; - } - var group: u64 = 0; - while (group < 4) { - var start: u64 = 16; - var words: u64 = state.instructions * 97; - if (group == 1) { - start = block_base; - words = state.blocks * 5; - } else if (group == 2) { - start = edge_base; - words = state.edges * 6; - } else if (group == 3) { - start = stop_base; - words = state.stops * 4; - } - i = 0; - while (i < words) { - output[start + i] = state.stage[start + i]; - i += 1; - } - group += 1; - } - return 0; -} diff --git a/src/builtins.rs b/src/builtins.rs index cf02788..9b540a8 100644 --- a/src/builtins.rs +++ b/src/builtins.rs @@ -4,9 +4,13 @@ pub fn registry() -> toolchain::Registry { registry .register_target(ir::Target::X86_64WhaleLinux.specification()) .expect("valid built-in target"); + #[cfg(feature = "asm-amd64")] registry.register_assembler(amd64::AMD64).expect("unique built-in assembler"); + #[cfg(feature = "asm-aarch64")] registry.register_assembler(aarch64::AArch64).expect("unique built-in assembler"); + #[cfg(feature = "asm-riscv64")] registry.register_assembler(riscv64::RiscV64).expect("unique built-in assembler"); + #[cfg(feature = "asm-loongarch64")] registry.register_assembler(loongarch64::LoongArch64).expect("unique built-in assembler"); registry } diff --git a/src/cli.rs b/src/cli.rs index 0425de7..1013d5e 100644 --- a/src/cli.rs +++ b/src/cli.rs @@ -50,7 +50,7 @@ fn print_help() { println!(" asm Assemble AMD64/AArch64/RV64I/LoongArch64 source into an ELF64 object"); println!(" object Wrap raw bytes in an AMD64 ELF64 object"); println!(" link Static Linux AMD64 executable linking"); - println!(" disasm AMD64 disassembly (requires the opt-in Wave reverse core)"); - println!(" reverse ELF inspection and Wave CFG/xref analysis"); + println!(" disasm Disassembly entry point (core currently unavailable)"); + println!(" reverse ELF inspection; CFG/xrefs core currently unavailable"); println!(" ir IR tools (verify/print/run; socket-cli enables AST lower)"); } diff --git a/src/commands/asm.rs b/src/commands/asm.rs index 1e74d3a..638b80b 100644 --- a/src/commands/asm.rs +++ b/src/commands/asm.rs @@ -6,10 +6,6 @@ use std::time::Instant; use super::debug::dump_bytes; -use amd64::parser::parse; - -use assembler::tokens::tokenize; - pub fn run(args: Vec) { if args.is_empty() { print_help(); @@ -207,39 +203,12 @@ pub fn run(args: Vec) { process::exit(1); }); - let mut token_len: Option = None; - let mut ast_items_len: Option = None; - let need_tokens = arch == "amd64" && debug_mode && (show_token || show_ast || show_stats); - if need_tokens { - if trace_enable { - println!("[trace] tokenize start"); - } - let tokens = tokenize(&src).unwrap_or_else(|e| { - eprintln!("Tokenize error: {}", e.with_source_name(&input)); - process::exit(1); - }); - token_len = Some(tokens.len()); - - if show_token { - dbg!(&tokens); - } - - if show_ast || show_stats { - if trace_enable { - println!("[trace] parse start"); - } - let ast = parse(&tokens).unwrap_or_else(|e| { - eprintln!("Parse error: {}", e.with_source_name(&input)); - process::exit(1); - }); - ast_items_len = Some(ast.items.len()); - - if show_ast { - println!("{:#?}", ast); - } - } - } + let (token_len, ast_items_len) = if need_tokens { + parser_debug(&input, &src, show_token, show_ast, show_stats, trace_enable) + } else { + (None, None) + }; if trace_enable { println!("[trace] assemble start"); @@ -256,7 +225,7 @@ pub fn run(args: Vec) { if trace_enable { println!("[trace] creating object file"); } - let final_bytes = asmobj::write(&out, target).unwrap_or_else(|e| { + let final_bytes = toolchain::assembly_object::write(&out, target).unwrap_or_else(|e| { eprintln!("Object build error: {}", e); process::exit(1); }); @@ -283,6 +252,56 @@ pub fn run(args: Vec) { println!("Wrote {} bytes to {}", final_bytes.len(), output); } +#[cfg(feature = "asm-amd64")] +fn parser_debug( + input: &str, + source: &str, + show_token: bool, + show_ast: bool, + show_stats: bool, + trace: bool, +) -> (Option, Option) { + if trace { + println!("[trace] tokenize start"); + } + let tokens = assembler::tokens::tokenize(source).unwrap_or_else(|e| { + eprintln!("Tokenize error: {}", e.with_source_name(input)); + process::exit(1); + }); + if show_token { + dbg!(&tokens); + } + let ast_items = if show_ast || show_stats { + if trace { + println!("[trace] parse start"); + } + let ast = amd64::parser::parse(&tokens).unwrap_or_else(|e| { + eprintln!("Parse error: {}", e.with_source_name(input)); + process::exit(1); + }); + let count = ast.items.len(); + if show_ast { + println!("{:#?}", ast); + } + Some(count) + } else { + None + }; + (Some(tokens.len()), ast_items) +} + +#[cfg(not(feature = "asm-amd64"))] +fn parser_debug( + _: &str, + _: &str, + _: bool, + _: bool, + _: bool, + _: bool, +) -> (Option, Option) { + (None, None) +} + fn print_help() { println!("Usage:"); println!(" whale asm --amd64|--aarch64|--arm64|--riscv64|--loongarch64 -o "); diff --git a/tests/module_selection.rs b/tests/module_selection.rs new file mode 100644 index 0000000..94e7430 --- /dev/null +++ b/tests/module_selection.rs @@ -0,0 +1,21 @@ +//! Reduced products must not acquire all ISAs through the composition root. +#[test] +fn registry_contains_exactly_the_selected_assemblers() { + let registry = whale::builtins::registry(); + let mut expected = Vec::new(); + if cfg!(feature = "asm-amd64") { + expected.push("amd64"); + } + if cfg!(feature = "asm-aarch64") { + expected.push("aarch64"); + } + if cfg!(feature = "asm-riscv64") { + expected.push("riscv64"); + } + if cfg!(feature = "asm-loongarch64") { + expected.push("loongarch64"); + } + expected.sort_unstable(); + assert_eq!(registry.assembler_ids().collect::>(), expected); + assert!(registry.target("x86_64-whale-linux").is_some()); +} diff --git a/tests/multi_isa.rs b/tests/multi_isa.rs index 984e49c..48fb314 100644 --- a/tests/multi_isa.rs +++ b/tests/multi_isa.rs @@ -140,7 +140,7 @@ fn elf_identity_symbol_relocations_and_sparse_bss_are_preserved() { let source=format!(".text\n.global entry\n.extern external\nentry: {call} external+4\nret\n.data\npayload: .quad entry+8\n.word external-4\n.bss\n.balign 4096\nstorage: .zero 1099511627776\n"); let output = assemble(arch, &source); let target = ObjectTarget::elf64(machine); - let object = asmobj::to_object(&output, target).unwrap(); + let object = toolchain::assembly_object::to_object(&output, target).unwrap(); assert_eq!(object.relocations[0].kind, RelocKind::TargetSpecific { machine, code }); let bytes = object.write().unwrap(); assert_eq!(&bytes[..7], b"\x7fELF\x02\x01\x01"); @@ -345,13 +345,13 @@ fn shared_directives_limits_diagnostics_and_symbol_validation() { #[test] fn mismatched_relocation_namespaces_and_symbol_sections_never_serialize() { let mut out = assemble("aarch64", ".extern x\nbl x"); - assert!(asmobj::write(&out, ObjectTarget::elf64(Machine::RiscV64)).is_err()); + assert!(toolchain::assembly_object::write(&out, ObjectTarget::elf64(Machine::RiscV64)).is_err()); out.sections[0].relocs[0].kind = assembler::RelocKind::TargetSpecific { namespace: "unknown".into(), code: 283 }; - assert!(asmobj::write(&out, ObjectTarget::elf64(Machine::AArch64)).is_err()); + assert!(toolchain::assembly_object::write(&out, ObjectTarget::elf64(Machine::AArch64)).is_err()); out.sections[0].relocs.clear(); out.symbols[0].section_index = Some(999); - assert!(asmobj::write(&out, ObjectTarget::elf64(Machine::AArch64)).is_err()); + assert!(toolchain::assembly_object::write(&out, ObjectTarget::elf64(Machine::AArch64)).is_err()); } #[test] diff --git a/tests/reverse_cli.rs b/tests/reverse_cli.rs index af1cf02..87dcc52 100644 --- a/tests/reverse_cli.rs +++ b/tests/reverse_cli.rs @@ -55,7 +55,7 @@ fn inspection_is_available_in_ordinary_builds_and_arguments_are_strict() { } #[test] -fn disassembly_is_wave_backed_and_preserves_input_and_failed_output() { +fn unavailable_disassembly_preserves_input_and_failed_output() { let dir = tempfile::tempdir().unwrap(); let input = dir.path().join("sample.o"); let bytes = object(); @@ -63,18 +63,10 @@ fn disassembly_is_wave_backed_and_preserves_input_and_failed_output() { let output = dir.path().join("listing"); fs::write(&output, b"old").unwrap(); let result = whale().arg("disasm").arg(&input).arg("--json").output().unwrap(); - if reverse::backend_available() { - assert!(result.status.success(), "{}", String::from_utf8_lossy(&result.stderr)); - let v: serde_json::Value = serde_json::from_slice(&result.stdout).unwrap(); - let inst = &v["records"][0]["instruction"]; - assert_eq!(inst["mnemonic"], "call"); - assert!(inst["target"].is_null()); - assert_eq!(inst["relocations"][0]["symbol"], "external"); - assert_eq!(inst["bytes"], serde_json::json!([232, 0, 0, 0, 0])); - } else { - assert!(!result.status.success()); - assert!(String::from_utf8_lossy(&result.stderr).contains("Wave reverse core unavailable")); - } + assert!(!reverse::backend_available()); + assert!(!result.status.success()); + assert!(result.stdout.is_empty()); + assert!(String::from_utf8_lossy(&result.stderr).contains("reverse decoder is unavailable")); assert!(!whale() .arg("disasm") .arg(&input) @@ -98,79 +90,9 @@ fn disassembly_is_wave_backed_and_preserves_input_and_failed_output() { assert_eq!(fs::read(&output).unwrap(), b"old"); } -#[test] -fn raw_listing_keeps_unknown_bytes_and_enforces_decode_budget() { - if !reverse::backend_available() { - return; - } - let dir = tempfile::tempdir().unwrap(); - let input = dir.path().join("bytes"); - fs::write(&input, [0x90, 0x0f]).unwrap(); - let result = whale() - .args(["disasm", "--raw", "--amd64", "--base", "0x1000"]) - .arg(&input) - .arg("--json") - .output() - .unwrap(); - assert!(result.status.success()); - let v: serde_json::Value = serde_json::from_slice(&result.stdout).unwrap(); - assert_eq!(v["records"][0]["instruction"]["mnemonic"], "nop"); - assert_eq!(v["records"][1]["byte"], 15); - assert_eq!(v["records"][1]["code"], false); - assert!(!whale() - .args(["disasm", "--raw", "--amd64", "--base", "0x1000", "--max-instructions", "1"]) - .arg(input) - .output() - .unwrap() - .status - .success()); -} - -fn graph_json(command: &mut Command) -> serde_json::Value { - let result = command.arg("--json").output().unwrap(); - assert!(result.status.success(), "{}", String::from_utf8_lossy(&result.stderr)); - serde_json::from_slice(&result.stdout).unwrap() -} - -fn graph_offsets(graph: &serde_json::Value) -> Vec { - let mut offsets: Vec<_> = graph["instructions"] - .as_array() - .unwrap() - .iter() - .map(|instruction| instruction["offset"].as_u64().unwrap()) - .collect(); - offsets.sort_unstable(); - offsets -} - -fn sectionless_executable(code: &[u8], entry_offset: u64) -> Vec { - let mut bytes = vec![0; 120]; - bytes[..7].copy_from_slice(b"\x7fELF\x02\x01\x01"); - for (at, value) in [(16, 2u16), (18, 62), (52, 64), (54, 56), (56, 1)] { - bytes[at..at + 2].copy_from_slice(&value.to_le_bytes()); - } - for (at, value) in [(20, 1u32), (64, 1), (68, 5)] { - bytes[at..at + 4].copy_from_slice(&value.to_le_bytes()); - } - for (at, value) in [ - (24, 0x400078 + entry_offset), - (32, 64), - (80, 0x400000), - (96, 120 + code.len() as u64), - (104, 120 + code.len() as u64), - (112, 4096), - ] { - bytes[at..at + 8].copy_from_slice(&value.to_le_bytes()); - } - bytes.extend_from_slice(code); - bytes -} - #[test] fn ordinary_build_reports_cfg_and_xrefs_core_unavailable_explicitly() { - if reverse::backend_available() { - return; - } + assert!(!reverse::backend_available()); let dir = tempfile::tempdir().unwrap(); let input = dir.path().join("ret"); fs::write(&input, [0xc3]).unwrap(); @@ -182,7 +104,8 @@ fn ordinary_build_reports_cfg_and_xrefs_core_unavailable_explicitly() { .unwrap(); assert!(!result.status.success()); assert!( - String::from_utf8_lossy(&result.stderr).contains("Wave CFG core unavailable"), + String::from_utf8_lossy(&result.stderr) + .contains("control-flow analysis is unavailable"), "{}", String::from_utf8_lossy(&result.stderr) ); @@ -191,223 +114,10 @@ fn ordinary_build_reports_cfg_and_xrefs_core_unavailable_explicitly() { } #[test] -fn sectionless_executable_graph_starts_at_elf_entry_and_follows_backward_helpers() { - if !reverse::backend_available() { - return; - } - let dir = tempfile::tempdir().unwrap(); - let input = dir.path().join("sectionless"); - // The entry follows an unsupported gap; only the entry, its backward callee, - // and its continuation are reachable. The mapped ELF headers are not code. - let bytes = - sectionless_executable(&[0xc3, 0x0f, 0x0b, 0x90, 0xe8, 0xf7, 0xff, 0xff, 0xff, 0xc3], 4); - fs::write(&input, &bytes).unwrap(); - for mode in ["cfg", "xrefs"] { - let graph = graph_json(whale().args(["reverse", mode]).arg(&input)); - assert_eq!(graph["kind"], mode); - assert_eq!(graph["base"], 0x400000); - assert_eq!(graph["entry_offset"], 124); - assert_eq!(graph_offsets(&graph), [120, 124, 129]); - assert!(graph["stops"].as_array().unwrap().is_empty()); - assert!(graph["edges"].as_array().unwrap().iter().any(|edge| { - edge["from"] == 124 - && edge["kind"] == "Call" - && edge["target"]["kind"] == "address" - && edge["target"]["address"] == 0x400078 - })); - if mode == "xrefs" { - assert!(graph["edges"] - .as_array() - .unwrap() - .iter() - .all(|edge| edge["kind"] != "FallThrough")); - } - } - assert_eq!(fs::read(input).unwrap(), bytes); -} - -#[test] -fn raw_graph_accepts_explicit_entry_and_follows_backward_helpers() { - if !reverse::backend_available() { - return; - } - let dir = tempfile::tempdir().unwrap(); - let input = dir.path().join("raw"); - fs::write(&input, [0xc3, 0x0f, 0x0b, 0x90, 0xe8, 0xf7, 0xff, 0xff, 0xff, 0xc3]).unwrap(); - let graph = graph_json( - whale() - .args(["reverse", "cfg", "--raw", "--amd64", "--base", "0x1000", "--entry", "0x1004"]) - .arg(&input), - ); - assert_eq!(graph["entry_offset"], 4); - assert_eq!(graph_offsets(&graph), [0, 4, 9]); - assert!(graph["edges"].as_array().unwrap().iter().any(|edge| { - edge["from"] == 4 && edge["kind"] == "Call" && edge["target"]["address"] == 0x1000 - })); -} - -#[test] -fn relocatable_graph_requires_entry_and_preserves_symbolic_external_calls() { - if !reverse::backend_available() { - return; - } - let dir = tempfile::tempdir().unwrap(); - let input = dir.path().join("external.o"); - fs::write(&input, object()).unwrap(); - for mode in ["cfg", "xrefs"] { - let missing = whale().args(["reverse", mode]).arg(&input).output().unwrap(); - assert!(!missing.status.success()); - assert!(String::from_utf8_lossy(&missing.stderr).contains("entry")); - let graph = graph_json(whale().args(["reverse", mode, "--entry", "0"]).arg(&input)); - assert_eq!(graph_offsets(&graph), [0, 5]); - let calls: Vec<_> = graph["edges"] - .as_array() - .unwrap() - .iter() - .filter(|edge| edge["kind"] == "Call") - .collect(); - assert_eq!(calls.len(), 1); - assert_eq!(calls[0]["target"]["kind"], "symbol"); - assert_eq!(calls[0]["target"]["name"], "external"); - assert!(calls[0]["target"]["address"].is_null()); - assert!(graph["instructions"][0]["target"].is_null()); - assert_eq!(graph["relocations"][0]["symbol"], "external"); - let text = whale().args(["reverse", mode, "--entry", "0"]).arg(&input).output().unwrap(); - assert!(text.status.success()); - assert!(String::from_utf8_lossy(&text.stdout).contains("symbol \"external\"")); - assert!(!String::from_utf8_lossy(&text.stdout).contains("Call -> 0x5")); - } -} - -#[test] -fn relocatable_graph_defaults_to_start_and_keeps_one_code_region_scope() { - if !reverse::backend_available() { - return; - } - use object::*; - let mut object = ObjectFile::new(ObjectFormat::ELF64); - object.add_section(".text", SectionKind::Text, 1); - object.add_section(".text.other", SectionKind::Text, 1); - object.sections[0].data = vec![0xc3]; - object.sections[1].data = vec![0xc5]; - object.symbols.push(ObjectSymbol { - name: "_start".into(), - section_index: Some(0), - value: 0, - size: 1, - binding: SymbolBinding::Global, - kind: SymbolKind::Function, - visibility: SymbolVisibility::Default, - }); - let dir = tempfile::tempdir().unwrap(); - let input = dir.path().join("regions.o"); - fs::write(&input, object.write().unwrap()).unwrap(); - for mode in ["cfg", "xrefs"] { - let graph = graph_json(whale().args(["reverse", mode]).arg(&input)); - assert_eq!(graph["region"], 0); - assert_eq!(graph_offsets(&graph), [0]); - assert!(graph["stops"].as_array().unwrap().is_empty()); - let ambiguous = - whale().args(["reverse", mode, "--entry", "0"]).arg(&input).output().unwrap(); - assert!(!ambiguous.status.success()); - assert!(String::from_utf8_lossy(&ambiguous.stderr).contains("ambiguous")); - } -} - -#[test] -fn graph_distinguishes_indirect_targets_overlap_and_unknown_stops() { - if !reverse::backend_available() { - return; - } - let dir = tempfile::tempdir().unwrap(); - let input = dir.path().join("raw"); - fs::write(&input, [0xff, 0xd0, 0xff, 0xe0, 0xc3]).unwrap(); - for mode in ["cfg", "xrefs"] { - let graph = graph_json( - whale().args(["reverse", mode, "--raw", "--amd64", "--base", "0x1000"]).arg(&input), - ); - assert_eq!(graph_offsets(&graph), [0, 2]); - for kind in ["IndirectCall", "IndirectJump"] { - assert!(graph["edges"] - .as_array() - .unwrap() - .iter() - .any(|edge| { edge["kind"] == kind && edge["target"]["kind"] == "unresolved" })); - } - assert!(graph["stops"] - .as_array() - .unwrap() - .iter() - .any(|stop| { stop["kind"] == "IndirectJump" && stop["offset"] == 2 })); - } - for (bytes, stop_kind, offset, conflict) in [ - (vec![0xeb, 0xff], "Overlap", 1, Some(0)), - (vec![0xc5], "Unsupported", 0, None), - (vec![0x48, 0xb8], "Truncated", 0, None), - ] { - fs::write(&input, bytes).unwrap(); - let graph = graph_json( - whale().args(["reverse", "cfg", "--raw", "--amd64", "--base", "0x1000"]).arg(&input), - ); - assert!(graph["stops"].as_array().unwrap().iter().any(|stop| { - stop["kind"] == stop_kind - && stop["offset"] == offset - && stop["conflict"] == serde_json::json!(conflict) - })); - } -} - -#[test] -fn graph_output_limit_is_exact_and_failed_publication_preserves_files() { - if !reverse::backend_available() { - return; - } - let dir = tempfile::tempdir().unwrap(); - let input = dir.path().join("raw"); - let bytes = [0x90, 0xc3]; - fs::write(&input, bytes).unwrap(); - let output = dir.path().join("graph"); - for mode in ["cfg", "xrefs"] { - for structured in [false, true] { - let command = || { - let mut command = whale(); - command.args(["reverse", mode, "--raw", "--amd64", "--base", "0x1000"]).arg(&input); - if structured { - command.arg("--json"); - } - command - }; - let complete = command().output().unwrap(); - assert!(complete.status.success()); - let exact = command() - .args(["--max-output", &complete.stdout.len().to_string()]) - .output() - .unwrap(); - assert!(exact.status.success()); - assert_eq!(exact.stdout, complete.stdout); - fs::write(&output, b"old").unwrap(); - let short = command() - .args(["--max-output", &(complete.stdout.len() - 1).to_string()]) - .arg("-o") - .arg(&output) - .output() - .unwrap(); - assert!(!short.status.success()); - assert!(String::from_utf8_lossy(&short.stderr).contains("output byte limit")); - assert!(short.stdout.is_empty()); - assert_eq!(fs::read(&output).unwrap(), b"old"); - assert!(!command().arg("-o").arg(&input).output().unwrap().status.success()); - assert_eq!(fs::read(&input).unwrap(), bytes); - } - } -} - -#[test] -fn graph_budget_options_are_validated_and_enforced_before_output_publication() { +fn graph_budget_options_are_validated_without_an_analysis_backend() { let dir = tempfile::tempdir().unwrap(); let input = dir.path().join("raw"); fs::write(&input, [0x90, 0xc3]).unwrap(); - let output = dir.path().join("graph"); for mode in ["cfg", "xrefs"] { for (flag, value) in [ ("--max-work", "0"), @@ -424,30 +134,6 @@ fn graph_budget_options_are_validated_and_enforced_before_output_publication() { assert!(!result.status.success()); assert!(String::from_utf8_lossy(&result.stderr).contains(flag)); } - if reverse::backend_available() { - for (flag, resource) in [ - ("--max-instructions", "Instructions"), - ("--max-work", "Work"), - ("--max-workspace", "Memory"), - ] { - fs::write(&output, b"old").unwrap(); - let result = whale() - .args(["reverse", mode, "--raw", "--amd64", "--base", "0"]) - .arg(&input) - .args([flag, "1", "-o"]) - .arg(&output) - .output() - .unwrap(); - assert!(!result.status.success()); - assert!( - String::from_utf8_lossy(&result.stderr).contains(resource), - "{}", - String::from_utf8_lossy(&result.stderr) - ); - assert!(result.stdout.is_empty()); - assert_eq!(fs::read(&output).unwrap(), b"old"); - } - } } } @@ -516,28 +202,3 @@ fn static_inspection_preserves_boundary_markers_and_omits_tls_offsets() { assert!(symbols[1]["region"].is_null()); assert_eq!(symbols[1]["address"], 0x500000); } - -#[test] -fn stack_rex_w_immediate_boundary_is_preserved_by_public_listing_and_cfg() { - if !reverse::backend_available() { - return; - } - let dir = tempfile::tempdir().unwrap(); - let input = dir.path().join("stack-prefix"); - fs::write(&input, [0x66, 0x48, 0x68, 0x34, 0x12, 0xc3, 0x56, 0xc3]).unwrap(); - let listing = whale() - .arg("disasm") - .arg(&input) - .args(["--raw", "--amd64", "--base", "0", "--json"]) - .output() - .unwrap(); - assert!(listing.status.success(), "{}", String::from_utf8_lossy(&listing.stderr)); - let listing: serde_json::Value = serde_json::from_slice(&listing.stdout).unwrap(); - assert_eq!(listing["records"].as_array().unwrap().len(), 2); - assert_eq!(listing["records"][0]["instruction"]["length"], 7); - let graph = graph_json( - whale().args(["reverse", "cfg"]).arg(input).args(["--raw", "--amd64", "--base", "0"]), - ); - assert_eq!(graph_offsets(&graph), [0, 7]); - assert_eq!(graph["blocks"][0]["end"], 8); -} diff --git a/toolchain/Cargo.toml b/toolchain/Cargo.toml index 33f0b55..149eed0 100644 --- a/toolchain/Cargo.toml +++ b/toolchain/Cargo.toml @@ -10,3 +10,4 @@ backend-api = { path = "../backend-api" } target-spec = { path = "../target-spec" } ir = { path = "../ir" } diagnostic = { path = "../diagnostic" } +object = { path = "../object" } diff --git a/toolchain/build.rs b/toolchain/build.rs new file mode 100644 index 0000000..3402119 --- /dev/null +++ b/toolchain/build.rs @@ -0,0 +1,86 @@ +// SPDX-License-Identifier: MPL-2.0 +use std::{env, fs, io::Read, path::PathBuf}; + +fn update(hash: u64, bytes: &[u8]) -> u64 { + bytes.iter().fold(hash, |h, b| (h ^ u64::from(*b)).wrapping_mul(0x100000001b3)) +} + +fn hash(bytes: &[u8]) -> String { + format!("{:016x}", update(0xcbf29ce484222325, bytes)) +} + +fn archive_hash(path: &std::path::Path) -> String { + let mut file = fs::File::open(path).expect("missing asmobj archive"); + let mut hash = 0xcbf29ce484222325; + let mut buffer = [0; 16384]; + loop { + let count = file.read(&mut buffer).expect("cannot read asmobj archive"); + if count == 0 { + return format!("{hash:016x}"); + } + hash = update(hash, &buffer[..count]); + } +} + +fn main() { + println!("cargo:rustc-check-cfg=cfg(whale_asmobj)"); + println!("cargo:rerun-if-env-changed=WHALE_ASMOBJ_DIR"); + let Some(directory) = env::var_os("WHALE_ASMOBJ_DIR") else { return }; + let directory = PathBuf::from(directory).canonicalize().expect("WHALE_ASMOBJ_DIR must exist"); + let target = env::var("TARGET").unwrap(); + let archive = directory.join(if target.contains("msvc") { + "whale_asmobj.lib" + } else { + "libwhale_asmobj.a" + }); + let metadata = directory.join("asmobj.meta"); + println!("cargo:rerun-if-changed={}", archive.display()); + println!("cargo:rerun-if-changed={}", metadata.display()); + let mut text = String::new(); + fs::File::open(&metadata) + .expect("missing asmobj.meta; build with tools/build_asmobj.py") + .take(4097) + .read_to_string(&mut text) + .expect("invalid asmobj metadata"); + assert!(text.len() <= 4096, "oversized asmobj metadata"); + let mut fields = std::collections::BTreeMap::new(); + for line in text.lines() { + let (key, value) = line.split_once('=').expect("malformed asmobj metadata"); + assert!( + ["schema", "target", "source_fnv64", "archive_fnv64"].contains(&key) + && fields.insert(key, value).is_none(), + "invalid asmobj metadata fields" + ); + } + assert_eq!(fields.len(), 4, "incomplete asmobj metadata"); + assert_eq!(fields.get("schema"), Some(&"1"), "unsupported asmobj metadata"); + assert_eq!(fields.get("target"), Some(&target.as_str()), "asmobj archive target mismatch"); + let root = + PathBuf::from(env::var_os("CARGO_MANIFEST_DIR").unwrap()).join("../assembler/asmobj"); + let mut source = Vec::new(); + for (index, name) in + ["model.wave", "sections.wave", "symbols.wave", "relocations.wave", "entry.wave"] + .iter() + .enumerate() + { + let path = root.join(name); + println!("cargo:rerun-if-changed={}", path.display()); + if index != 0 { + source.push(b'\n'); + } + source.extend(fs::read(path).expect("missing asmobj Wave source")); + } + assert_eq!( + fields.get("source_fnv64"), + Some(&hash(&source).as_str()), + "stale asmobj archive; rebuild with tools/build_asmobj.py" + ); + assert_eq!( + fields.get("archive_fnv64"), + Some(&archive_hash(&archive).as_str()), + "corrupt asmobj archive" + ); + println!("cargo:rustc-link-search=native={}", directory.display()); + println!("cargo:rustc-link-lib=static=whale_asmobj"); + println!("cargo:rustc-cfg=whale_asmobj"); +} diff --git a/toolchain/src/assembly_object.rs b/toolchain/src/assembly_object.rs new file mode 100644 index 0000000..533449c --- /dev/null +++ b/toolchain/src/assembly_object.rs @@ -0,0 +1,416 @@ +// SPDX-License-Identifier: MPL-2.0 +//! Host-side data transport for the complete Wave `assembler/asmobj` module. +//! No relocation selection or symbol-resolution policy belongs in this file. +use assembler::AssemblerOutput; + +use object::{ObjectFile, ObjectTarget}; + +/// Whether this product links the Wave assembler-to-object module. +pub const fn available() -> bool { + cfg!(whale_asmobj) +} + +pub fn write(input: &AssemblerOutput, target: ObjectTarget) -> Result, String> { + to_object(input, target)?.write() +} + +pub fn to_object(input: &AssemblerOutput, target: ObjectTarget) -> Result { + #[cfg(whale_asmobj)] + { + native::convert(input, target) + } + #[cfg(not(whale_asmobj))] + { + let _ = (input, target); + Err("asmobj module is unavailable; build with Meson or set WHALE_ASMOBJ_DIR to its built archive".into()) + } +} + +#[cfg(whale_asmobj)] +mod native { + use super::*; + + use assembler::assembler::RelocKind as AReloc; + + use assembler::{AsmSectionKind, SymbolKind, SymbolVisibility}; + + use object::{ + Machine, ObjectFormat, ObjectRelocation, ObjectSymbol, RelocKind, Section, SectionKind, + SymbolBinding, + }; + + use std::collections::HashMap; + + #[repr(C)] + struct Target { + format: u64, + machine: u64, + address_bits: u64, + endian: u64, + } + + #[repr(C)] + #[derive(Clone, Copy)] + struct SectionRow { + name: *const u8, + name_len: u64, + kind: u64, + align: u64, + data: *const u8, + data_len: u64, + zero_fill: u64, + } + + #[repr(C)] + #[derive(Clone, Copy)] + struct SymbolRow { + name: *const u8, + name_len: u64, + kind: u64, + section: u64, + offset: u64, + size: u64, + binding: u64, + visibility: u64, + } + + #[repr(C)] + #[derive(Clone, Copy)] + struct RelocRow { + section: u64, + offset: u64, + name: *const u8, + name_len: u64, + kind: u64, + namespace: *const u8, + namespace_len: u64, + code: u64, + addend: i64, + } + + #[repr(C)] + #[derive(Default)] + struct ResultRow { + status: u64, + index: u64, + symbol_count: u64, + } + + unsafe extern "C" { + fn whale_asmobj( + target: *const Target, + sections: *const SectionRow, + section_count: u64, + symbols: *const SymbolRow, + symbol_count: u64, + relocations: *const RelocRow, + relocation_count: u64, + out_sections: *mut SectionRow, + section_capacity: u64, + out_symbols: *mut SymbolRow, + symbol_capacity: u64, + out_relocations: *mut RelocRow, + relocation_capacity: u64, + scratch: *mut u64, + scratch_words: u64, + result: *mut ResultRow, + ) -> i32; + } + + fn invalid() -> String { + "invalid output from asmobj module".into() + } + + fn allocate(length: usize, value: T) -> Result, String> { + let mut items = Vec::new(); + items.try_reserve_exact(length).map_err(|_| "asmobj allocation failed")?; + items.resize(length, value); + Ok(items) + } + + fn host(value: u64) -> Result { + usize::try_from(value).map_err(|_| invalid()) + } + + fn name<'a>( + table: &'a HashMap<(*const u8, u64), &str>, + pointer: *const u8, + length: u64, + ) -> Result<&'a str, String> { + table.get(&(pointer, length)).copied().ok_or_else(invalid) + } + + pub(super) fn convert( + input: &AssemblerOutput, + target: ObjectTarget, + ) -> Result { + let ns = input.sections.len(); + let ny = input.symbols.len(); + let nr = input + .sections + .iter() + .try_fold(0usize, |n, s| n.checked_add(s.relocs.len())) + .ok_or("asmobj input limit exceeded")?; + let total = ns + .checked_add(ny) + .and_then(|n| n.checked_add(nr)) + .ok_or("asmobj input limit exceeded")?; + if total > 262_144 { + return Err("asmobj input limit exceeded".into()); + } + let symbols_capacity = ny + nr; + let scratch_words = + if symbols_capacity == 0 { 0 } else { symbols_capacity.next_power_of_two() * 8 }; + let mut names = HashMap::new(); + names.try_reserve(total).map_err(|_| "asmobj allocation failed")?; + let mut sections = Vec::new(); + sections.try_reserve_exact(ns).map_err(|_| "asmobj allocation failed")?; + let mut symbols = Vec::new(); + symbols.try_reserve_exact(ny).map_err(|_| "asmobj allocation failed")?; + let mut relocs = Vec::new(); + relocs.try_reserve_exact(nr).map_err(|_| "asmobj allocation failed")?; + for section in &input.sections { + names.insert((section.name.as_ptr(), section.name.len() as u64), section.name.as_str()); + sections.push(SectionRow { + name: section.name.as_ptr(), + name_len: section.name.len() as u64, + kind: match section.kind { + AsmSectionKind::Text => 0, + AsmSectionKind::Data => 1, + AsmSectionKind::ReadOnlyData => 2, + AsmSectionKind::Bss => 3, + }, + align: section.align, + data: section.data.as_ptr(), + data_len: section.data.len() as u64, + zero_fill: section.zero_fill, + }); + } + for symbol in &input.symbols { + names.insert((symbol.name.as_ptr(), symbol.name.len() as u64), symbol.name.as_str()); + symbols.push(SymbolRow { + name: symbol.name.as_ptr(), + name_len: symbol.name.len() as u64, + kind: match symbol.kind { + SymbolKind::NoType => 0, + SymbolKind::Function => 1, + SymbolKind::Object => 2, + }, + section: symbol.section_index.map_or(u64::MAX, |i| i as u64), + offset: symbol.offset, + size: symbol.size, + binding: u64::from(symbol.is_global), + visibility: match symbol.visibility { + SymbolVisibility::Default => 0, + SymbolVisibility::Hidden => 1, + }, + }); + } + for (index, section) in input.sections.iter().enumerate() { + for reloc in §ion.relocs { + names.insert( + (reloc.symbol.as_ptr(), reloc.symbol.len() as u64), + reloc.symbol.as_str(), + ); + let (kind, namespace, code) = match &reloc.kind { + AReloc::Absolute64 => (0, "", 0), + AReloc::Absolute32 => (1, "", 0), + AReloc::SignedAbsolute32 => (2, "", 0), + AReloc::Relative32 => (3, "", 0), + AReloc::Branch32 => (4, "", 0), + AReloc::Relative8 => (5, "", 0), + AReloc::TargetSpecific { namespace, code } => { + (6, namespace.as_str(), u64::from(*code)) + }, + }; + relocs.push(RelocRow { + section: index as u64, + offset: reloc.offset as u64, + name: reloc.symbol.as_ptr(), + name_len: reloc.symbol.len() as u64, + kind, + namespace: namespace.as_ptr(), + namespace_len: namespace.len() as u64, + code, + addend: reloc.addend, + }); + } + } + let blank_section = SectionRow { + name: std::ptr::null(), + name_len: 0, + kind: 0, + align: 0, + data: std::ptr::null(), + data_len: 0, + zero_fill: 0, + }; + let blank_symbol = SymbolRow { + name: std::ptr::null(), + name_len: 0, + kind: 0, + section: 0, + offset: 0, + size: 0, + binding: 0, + visibility: 0, + }; + let blank_reloc = RelocRow { + section: 0, + offset: 0, + name: std::ptr::null(), + name_len: 0, + kind: 0, + namespace: std::ptr::null(), + namespace_len: 0, + code: 0, + addend: 0, + }; + let mut out_sections = allocate(ns, blank_section)?; + let mut out_symbols = allocate(symbols_capacity, blank_symbol)?; + let mut out_relocs = allocate(nr, blank_reloc)?; + let mut scratch = allocate(scratch_words, 0u64)?; + let mut result = ResultRow::default(); + let raw_target = Target { + format: match target.format { + ObjectFormat::ELF64 => 0, + ObjectFormat::COFF => 1, + ObjectFormat::MachO64 => 2, + }, + machine: match target.machine { + Machine::X86_64 => 0, + Machine::AArch64 => 1, + Machine::RiscV64 => 2, + Machine::LoongArch64 => 3, + }, + address_bits: u64::from(target.address_bits), + endian: match target.endian { + object::Endian::Little => 0, + object::Endian::Big => 1, + }, + }; + // All rows borrow live immutable input. Output arrays/scratch have exact + // advertised initialized lengths. The private Wave call retains nothing. + let status = unsafe { + whale_asmobj( + &raw_target, + sections.as_ptr(), + ns as u64, + symbols.as_ptr(), + ny as u64, + relocs.as_ptr(), + nr as u64, + out_sections.as_mut_ptr(), + ns as u64, + out_symbols.as_mut_ptr(), + symbols_capacity as u64, + out_relocs.as_mut_ptr(), + nr as u64, + scratch.as_mut_ptr(), + scratch_words as u64, + &mut result, + ) + }; + if i64::from(status) != result.status as i64 { + return Err(invalid()); + } + if status != 0 { + return Err(match status { + 1 => "unsupported object target".into(), + 2 => "symbol section index is invalid".into(), + 3 => "unsupported relocation namespace".into(), + 4 => "relocation namespace does not match object target".into(), + 5 => "unsupported AArch64 COFF instruction relocation".into(), + 6 => "assembler relocation namespace does not support this format".into(), + 7 => "asmobj output capacity exceeded".into(), + 8 => "invalid asmobj input".into(), + 9 => "asmobj work limit exceeded".into(), + _ => invalid(), + }); + } + let count = host(result.symbol_count)?; + if count > out_symbols.len() { + return Err(invalid()); + } + let mut object = ObjectFile::with_target(target); + for (index, row) in out_sections.iter().enumerate() { + let source = &input.sections[index]; + if row.data != source.data.as_ptr() || row.data_len != source.data.len() as u64 { + return Err(invalid()); + } + object.sections.push(Section { + name: name(&names, row.name, row.name_len)?.into(), + kind: match row.kind { + 0 => SectionKind::Text, + 1 => SectionKind::Data, + 2 => SectionKind::Bss, + 3 => SectionKind::ReadOnlyData, + _ => return Err(invalid()), + }, + align: row.align, + data: source.data.clone(), + zero_fill: row.zero_fill, + }); + } + for row in &out_symbols[..count] { + object.symbols.push(ObjectSymbol { + name: name(&names, row.name, row.name_len)?.into(), + kind: match row.kind { + 0 => object::SymbolKind::NoType, + 1 => object::SymbolKind::Function, + 2 => object::SymbolKind::Object, + _ => return Err(invalid()), + }, + section_index: if row.section == u64::MAX { + None + } else { + Some(host(row.section)?) + }, + value: row.offset, + size: row.size, + binding: match row.binding { + 0 => SymbolBinding::Local, + 1 => SymbolBinding::Global, + _ => return Err(invalid()), + }, + visibility: match row.visibility { + 0 => object::SymbolVisibility::Default, + 1 => object::SymbolVisibility::Hidden, + _ => return Err(invalid()), + }, + }); + } + for row in &out_relocs { + let kind = match row.kind { + 0 => RelocKind::Absolute64, + 1 => RelocKind::Absolute32, + 2 => RelocKind::SignedAbsolute32, + 3 => RelocKind::Relative32, + 4 => RelocKind::PLT32, + 5 => RelocKind::Relative8, + 6 => RelocKind::TargetSpecific { + machine: target.machine, + code: u32::try_from(row.code).map_err(|_| invalid())?, + }, + 7 => RelocKind::CoffSpecific { + machine: target.machine, + code: u16::try_from(row.code).map_err(|_| invalid())?, + }, + 8 => RelocKind::MachSpecific { + machine: target.machine, + code: u8::try_from(row.code).map_err(|_| invalid())?, + }, + _ => return Err(invalid()), + }; + object.relocations.push(ObjectRelocation { + section_index: host(row.section)?, + offset: host(row.offset)?, + symbol: name(&names, row.name, row.name_len)?.into(), + addend: row.addend, + kind, + }); + } + object.validate()?; + Ok(object) + } +} diff --git a/toolchain/src/lib.rs b/toolchain/src/lib.rs index 3b0eb1d..cb5a5c1 100644 --- a/toolchain/src/lib.rs +++ b/toolchain/src/lib.rs @@ -1,5 +1,7 @@ // SPDX-License-Identifier: MPL-2.0 //! Explicit composition root. No built-in ISA, global state, or dynamic loader. +pub mod assembly_object; + use assembler::extension::Assembler; use backend_api::{Artifact, Backend}; diff --git a/toolchain/tests/assembly_object.rs b/toolchain/tests/assembly_object.rs new file mode 100644 index 0000000..7dc63cb --- /dev/null +++ b/toolchain/tests/assembly_object.rs @@ -0,0 +1,340 @@ +// SPDX-License-Identifier: MPL-2.0 +//! Independent public-contract cases for the complete Wave asmobj conversion. +use toolchain::assembly_object; + +#[cfg(not(whale_asmobj))] +#[test] +fn missing_module_is_an_explicit_error() { + let input = assembler::AssemblerOutput { sections: vec![], symbols: vec![] }; + assert!(!assembly_object::available()); + assert!(assembly_object::to_object(&input, object::Target::X86_64WhaleLinux.object_target()) + .err() + .unwrap() + .contains("unavailable")); +} + +#[cfg(whale_asmobj)] +mod native { + use super::*; + + use assembler::assembler::RelocKind as AsmReloc; + + use assembler::{AsmSection, AsmSectionKind, AsmSymbol, AssemblerOutput, Relocation}; + + use object::{Machine, ObjectFormat, ObjectTarget, RelocKind, SectionKind, SymbolBinding}; + + fn section(name: &str, kind: AsmSectionKind) -> AsmSection { + AsmSection { + name: name.into(), + kind, + align: 16, + data: if matches!(kind, AsmSectionKind::Bss) { vec![] } else { vec![0; 256] }, + zero_fill: if matches!(kind, AsmSectionKind::Bss) { 1 << 40 } else { 0 }, + relocs: vec![], + } + } + + fn symbol(name: &str, section_index: Option) -> AsmSymbol { + AsmSymbol { + name: name.into(), + section_index, + offset: if section_index.is_some() { 4 } else { 0 }, + size: if section_index.is_some() { 8 } else { 0 }, + is_global: section_index.is_none(), + kind: assembler::SymbolKind::Function, + visibility: assembler::SymbolVisibility::Hidden, + } + } + + fn fixture(relocations: Vec<(&str, AsmReloc)>) -> AssemblerOutput { + let mut section = section(".text", AsmSectionKind::Text); + section.relocs = relocations + .into_iter() + .enumerate() + .map(|(index, (symbol, kind))| Relocation { + offset: index * 8, + symbol: symbol.into(), + kind, + addend: -(index as i64), + }) + .collect(); + AssemblerOutput { + sections: vec![section], + symbols: vec![symbol("defined", Some(0)), symbol("declared", None)], + } + } + + fn target(format: ObjectFormat, machine: Machine) -> ObjectTarget { + ObjectTarget { format, machine, endian: object::Endian::Little, address_bits: 64 } + } + + fn specific(namespace: &str, code: u32) -> AsmReloc { + AsmReloc::TargetSpecific { namespace: namespace.into(), code } + } + + #[test] + fn all_generic_relocations_preserve_field_identity_and_order() { + assert!(assembly_object::available()); + let input = fixture(vec![ + ("defined", AsmReloc::Absolute64), + ("defined", AsmReloc::Absolute32), + ("defined", AsmReloc::SignedAbsolute32), + ("defined", AsmReloc::Relative32), + ("defined", AsmReloc::Relative8), + ("defined", AsmReloc::Branch32), + ("declared", AsmReloc::Branch32), + ]); + let output = + assembly_object::to_object(&input, ObjectTarget::elf64(Machine::X86_64)).unwrap(); + let expected = [ + RelocKind::Absolute64, + RelocKind::Absolute32, + RelocKind::SignedAbsolute32, + RelocKind::Relative32, + RelocKind::Relative8, + RelocKind::Relative32, + RelocKind::PLT32, + ]; + for (index, (relocation, kind)) in output.relocations.iter().zip(expected).enumerate() { + assert_eq!(relocation.kind, kind); + assert_eq!(relocation.section_index, 0); + assert_eq!(relocation.offset, index * 8); + assert_eq!(relocation.addend, -(index as i64)); + assert_eq!(relocation.symbol, input.sections[0].relocs[index].symbol); + } + assert_eq!(output.relocations.len(), expected.len()); + assert_eq!(output.symbols.len(), 2); + } + + #[test] + fn generic_relocation_format_support_matches_independent_contract_table() { + use RelocKind::{Absolute32, Absolute64, Relative32, Relative8, SignedAbsolute32, PLT32}; + let all = [ + Some(Absolute64), + Some(Absolute32), + Some(SignedAbsolute32), + Some(Relative32), + Some(PLT32), + Some(Relative8), + ]; + let absolute = [Some(Absolute64), Some(Absolute32), None, None, None, None]; + let coff_x64 = + [Some(Absolute64), Some(Absolute32), None, Some(Relative32), Some(PLT32), None]; + let macho_x64 = [ + Some(Absolute64), + None, + None, + Some(Relative32), + Some(RelocKind::MachSpecific { machine: Machine::X86_64, code: 2 }), + None, + ]; + let macho_arm = [ + Some(Absolute64), + None, + None, + None, + Some(RelocKind::MachSpecific { machine: Machine::AArch64, code: 2 }), + None, + ]; + for (target, expected) in [ + (ObjectTarget::elf64(Machine::X86_64), all), + (ObjectTarget::elf64(Machine::AArch64), absolute), + (ObjectTarget::elf64(Machine::RiscV64), absolute), + (ObjectTarget::elf64(Machine::LoongArch64), absolute), + (ObjectTarget::coff(Machine::X86_64), coff_x64), + (ObjectTarget::coff(Machine::AArch64), absolute), + (ObjectTarget::macho64(Machine::X86_64), macho_x64), + (ObjectTarget::macho64(Machine::AArch64), macho_arm), + ] { + for (kind, expected) in [ + AsmReloc::Absolute64, + AsmReloc::Absolute32, + AsmReloc::SignedAbsolute32, + AsmReloc::Relative32, + AsmReloc::Branch32, + AsmReloc::Relative8, + ] + .into_iter() + .zip(expected) + { + let input = fixture(vec![("declared", kind)]); + let actual = assembly_object::to_object(&input, target); + match expected { + Some(kind) => assert_eq!(actual.unwrap().relocations[0].kind, kind), + None => assert!( + actual.is_err(), + "unexpected generic relocation accepted for {target:?}" + ), + } + } + } + } + + #[test] + fn all_isa_specific_elf_codes_keep_their_machine_namespace() { + for (machine, namespace, codes) in [ + (Machine::AArch64, "aarch64", &[274, 280, 282, 283][..]), + (Machine::RiscV64, "riscv64", &[16, 17][..]), + (Machine::LoongArch64, "loongarch64", &[64, 65, 66][..]), + ] { + let input = fixture( + codes.iter().map(|code| ("declared", specific(namespace, *code))).collect(), + ); + let output = assembly_object::to_object(&input, ObjectTarget::elf64(machine)).unwrap(); + let actual = + output.relocations.iter().map(|relocation| relocation.kind).collect::>(); + let expected = codes + .iter() + .map(|code| RelocKind::TargetSpecific { machine, code: *code }) + .collect::>(); + assert_eq!(actual, expected); + } + } + + #[test] + fn arm64_coff_and_macho_relocations_use_format_specific_codes() { + for (format, code, expected) in [ + ( + ObjectFormat::COFF, + 274, + RelocKind::CoffSpecific { machine: Machine::AArch64, code: 5 }, + ), + ( + ObjectFormat::COFF, + 280, + RelocKind::CoffSpecific { machine: Machine::AArch64, code: 15 }, + ), + ( + ObjectFormat::COFF, + 282, + RelocKind::CoffSpecific { machine: Machine::AArch64, code: 3 }, + ), + ( + ObjectFormat::COFF, + 283, + RelocKind::CoffSpecific { machine: Machine::AArch64, code: 3 }, + ), + ( + ObjectFormat::MachO64, + 282, + RelocKind::MachSpecific { machine: Machine::AArch64, code: 2 }, + ), + ( + ObjectFormat::MachO64, + 283, + RelocKind::MachSpecific { machine: Machine::AArch64, code: 2 }, + ), + ] { + let input = fixture(vec![("declared", specific("aarch64", code))]); + let output = + assembly_object::to_object(&input, target(format, Machine::AArch64)).unwrap(); + assert_eq!(output.relocations[0].kind, expected); + } + for machine in [Machine::X86_64, Machine::AArch64] { + let input = + fixture(vec![("defined", AsmReloc::Branch32), ("missing", AsmReloc::Branch32)]); + let output = + assembly_object::to_object(&input, ObjectTarget::macho64(machine)).unwrap(); + assert!(output + .relocations + .iter() + .all(|relocation| relocation.kind == RelocKind::MachSpecific { machine, code: 2 })); + } + } + + #[test] + fn synthesized_symbols_deduplicate_by_utf8_bytes_and_keep_first_use_order() { + let input = fixture(vec![ + ("외부_b", AsmReloc::Branch32), + ("外部_a", AsmReloc::Branch32), + ("외부_b", AsmReloc::Absolute64), + ("declared", AsmReloc::Branch32), + ]); + let output = + assembly_object::to_object(&input, ObjectTarget::elf64(Machine::X86_64)).unwrap(); + assert_eq!( + output.symbols.iter().map(|symbol| symbol.name.as_str()).collect::>(), + ["defined", "declared", "외부_b", "外部_a"] + ); + for symbol in &output.symbols[2..] { + assert_eq!(symbol.section_index, None); + assert_eq!(symbol.binding, SymbolBinding::Global); + assert_eq!(symbol.kind, object::SymbolKind::NoType); + assert_eq!(symbol.visibility, object::SymbolVisibility::Default); + assert_eq!((symbol.value, symbol.size), (0, 0)); + } + assert_eq!(output.symbols[0].kind, object::SymbolKind::Function); + assert_eq!(output.symbols[0].binding, SymbolBinding::Local); + assert_eq!(output.symbols[0].visibility, object::SymbolVisibility::Hidden); + assert_eq!((output.symbols[0].value, output.symbols[0].size), (4, 8)); + assert_eq!(input.symbols.len(), 2); + assert_eq!(input.sections[0].relocs.len(), 4); + } + + #[test] + fn section_roles_and_sparse_bss_remain_exact() { + let input = AssemblerOutput { + sections: vec![ + section(".text", AsmSectionKind::Text), + section(".data", AsmSectionKind::Data), + section(".rodata", AsmSectionKind::ReadOnlyData), + section(".bss", AsmSectionKind::Bss), + ], + symbols: vec![], + }; + let output = + assembly_object::to_object(&input, ObjectTarget::elf64(Machine::X86_64)).unwrap(); + assert_eq!( + output.sections.iter().map(|section| section.kind).collect::>(), + [SectionKind::Text, SectionKind::Data, SectionKind::ReadOnlyData, SectionKind::Bss] + ); + for (actual, original) in output.sections.iter().zip(&input.sections) { + assert_eq!(actual.name, original.name); + assert_eq!(actual.align, original.align); + assert_eq!(actual.data, original.data); + assert_eq!(actual.zero_fill, original.zero_fill); + } + let bytes = output.write().unwrap(); + assert!(bytes.len() < 4096, "sparse BSS was materialized"); + assert_eq!(input.sections[3].zero_fill, 1 << 40); + } + + #[test] + fn target_namespace_and_symbol_errors_are_not_silently_reinterpreted() { + for (format, machine, namespace, code, message) in [ + ( + ObjectFormat::ELF64, + Machine::AArch64, + "unknown", + 282, + "unsupported relocation namespace", + ), + (ObjectFormat::ELF64, Machine::AArch64, "riscv64", 17, "namespace does not match"), + (ObjectFormat::COFF, Machine::AArch64, "aarch64", 999, "unsupported AArch64 COFF"), + ( + ObjectFormat::MachO64, + Machine::AArch64, + "aarch64", + 274, + "does not support this format", + ), + (ObjectFormat::COFF, Machine::RiscV64, "riscv64", 17, "unsupported object target"), + ] { + let input = fixture(vec![("declared", specific(namespace, code))]); + let error = assembly_object::to_object(&input, target(format, machine)).err().unwrap(); + assert!(error.contains(message), "{error}"); + } + let mut duplicate = fixture(vec![]); + duplicate.symbols.push(symbol("defined", None)); + assert!(assembly_object::to_object(&duplicate, ObjectTarget::elf64(Machine::X86_64)) + .err() + .unwrap() + .contains("duplicate symbol")); + let mut invalid = fixture(vec![]); + invalid.symbols[0].section_index = Some(2); + assert!(assembly_object::to_object(&invalid, ObjectTarget::elf64(Machine::X86_64)) + .err() + .unwrap() + .contains("symbol section index")); + } +} diff --git a/tools/build_asmobj.py b/tools/build_asmobj.py new file mode 100644 index 0000000..8d1c725 --- /dev/null +++ b/tools/build_asmobj.py @@ -0,0 +1,85 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: MPL-2.0 +"""Compile the complete asmobj Wave module; read the pinned compiler checkout only.""" +import argparse +import hashlib +import json +import os +from pathlib import Path +import tempfile +from wave_bootstrap import DEFAULT_RUST_TOOLCHAIN, WAVE_REVISION, ensure_bootstrap, run, digest + +SOURCES = ('model.wave', 'sections.wave', 'symbols.wave', 'relocations.wave', 'entry.wave') +TARGETS = ('x86_64-unknown-linux-gnu', 'aarch64-unknown-linux-gnu', + 'riscv64gc-unknown-linux-gnu', 'x86_64-pc-windows-msvc', + 'aarch64-pc-windows-msvc', 'x86_64-apple-darwin', 'aarch64-apple-darwin') + +def fnv64(data): + value = 0xcbf29ce484222325 + for octet in data: + value = ((value ^ octet) * 0x100000001b3) & 0xffffffffffffffff + return f'{value:016x}' + +def source_bytes(root): + return b'\n'.join((root / 'assembler/asmobj' / name).read_bytes() for name in SOURCES) + +def metadata(source, archive, target): + return (f'schema=1\ntarget={target}\nsource_fnv64={fnv64(source)}\n' + f'archive_fnv64={fnv64(archive)}\n') + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--wave-source', type=Path, required=True) + parser.add_argument('--out-dir', type=Path, required=True) + parser.add_argument('--bootstrap-dir', type=Path) + parser.add_argument('--rust-toolchain', default=DEFAULT_RUST_TOOLCHAIN) + parser.add_argument('--target', choices=TARGETS, default=TARGETS[0]) + parser.add_argument('--opt-level', choices=('0', '2'), default='2') + parser.add_argument('--allow-network', action='store_true') + args = parser.parse_args() + output = args.out_dir.resolve() + if output == args.wave_source.resolve() or output.is_relative_to(args.wave_source.resolve()): + parser.error('asmobj output must be outside the read-only Wave checkout') + output.mkdir(parents=True, exist_ok=True) + root = Path(__file__).resolve().parents[1] + source = source_bytes(root) + bootstrap = ensure_bootstrap(args.wave_source, args.bootstrap_dir or output / 'bootstrap-cache', + rust_toolchain=args.rust_toolchain, allow_network=args.allow_network) + # Only code generation is cross-target; this never executes a foreign object. + wave_target = args.target.replace('riscv64gc-', 'riscv64-') + environment = os.environ.copy() + environment['WAVE_STD_REVISION'] = WAVE_REVISION + with tempfile.TemporaryDirectory(prefix='.asmobj-', dir=output) as temporary: + temporary = Path(temporary) + kernel = temporary / 'asmobj.wave' + kernel.write_bytes(source) + obj = temporary / 'asmobj.o' + run([bootstrap.compiler, '-O' + args.opt_level, '-C', 'relocation-model=pic', + '--std-root', bootstrap.std_root, '--target=' + wave_target, 'build', kernel, + '--freestanding', '--emit=obj', '-o', obj, '--target-dir', temporary / 'build'], + cwd=temporary, env=environment) + name = 'whale_asmobj.lib' if 'msvc' in args.target else 'libwhale_asmobj.a' + archive = temporary / name + archive_format = ('darwin' if 'apple-darwin' in args.target else + 'coff' if 'msvc' in args.target else None) + archiver = [environment.get('AR', 'ar')] + if archive_format: + # Cross-format symbol indexes must match the consuming linker. + # LLVM ar supports these explicit formats; a host GNU ar must fail + # rather than publish an archive it cannot index correctly. + archiver.append('--format=' + archive_format) + run([*archiver, 'crsD', archive, obj]) + provenance = temporary / 'provenance.json' + provenance.write_text(json.dumps({'wave_revision': WAVE_REVISION, 'target': args.target, + 'opt_level': args.opt_level, 'source_sha256': hashlib.sha256(source).hexdigest(), + 'archive_sha256': digest(archive), 'compiler_sha256': digest(bootstrap.compiler), + 'std_sha256': bootstrap.metadata['std_sha256'], + 'bootstrap_provenance': str(bootstrap.provenance)}, indent=2) + '\n') + fingerprint = temporary / 'asmobj.meta' + fingerprint.write_text(metadata(source, archive.read_bytes(), args.target)) + for path in (archive, provenance, fingerprint): + os.replace(path, output / path.name) + print(f'WHALE_ASMOBJ_DIR={output}') + +if __name__ == '__main__': + main() diff --git a/tools/build_wave_elf.py b/tools/build_wave_elf.py deleted file mode 100644 index d09b531..0000000 --- a/tools/build_wave_elf.py +++ /dev/null @@ -1,44 +0,0 @@ -#!/usr/bin/env python3 -# SPDX-License-Identifier: MPL-2.0 -"""Build the optional Wave ELF module using a pinned source bootstrap compiler.""" -import argparse -import os -from pathlib import Path -import subprocess -import tempfile - -WAVE_REVISION = "8a465e30aeea4b817d925cdd0e8d08c1bb029c9a" - - -def main(): - parser = argparse.ArgumentParser(description=__doc__) - parser.add_argument("--wave-source", required=True, type=Path) - parser.add_argument("--out-dir", required=True, type=Path) - args = parser.parse_args() - source = args.wave_source.resolve() - revision = subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=source, text=True).strip() - if revision != WAVE_REVISION: - parser.error(f"expected Wave {WAVE_REVISION}, found {revision}") - dirty = subprocess.check_output(["git", "status", "--porcelain", "--untracked-files=no"], cwd=source, text=True) - if dirty: - parser.error("Wave bootstrap source has tracked modifications") - out = args.out_dir.resolve() - out.mkdir(parents=True, exist_ok=True) - # Rebuild from the verified sources rather than trusting an unrelated wavec. - subprocess.run(["cargo", "build", "--locked", "--manifest-path", str(source / "Cargo.toml"), "--target-dir", str(out / "bootstrap")], cwd=source, check=True) - compiler = out / "bootstrap/debug/wavec" - root = Path(__file__).resolve().parents[1] - obj = out / "elf_records.o" - subprocess.run([str(compiler), "-O0", "--target=x86_64-unknown-linux-gnu", "build", str(root / "object/wave/elf_records.wave"), "--freestanding", "--emit=obj", "-o", str(obj), "--target-dir", str(out / "wave-build")], check=True) - archive = out / "libwhale_wave_elf.a" - # The temporary archive is on the destination filesystem. Neither a failed - # archiver nor a failed publication may delete the last good artifact. - with tempfile.TemporaryDirectory(prefix=".whale-wave-", dir=out) as temporary: - candidate = Path(temporary) / archive.name - subprocess.run([os.environ.get("AR", "ar"), "crsD", str(candidate), str(obj)], check=True) - os.replace(candidate, archive) - print(f"WHALE_WAVE_ELF_DIR={out}") - - -if __name__ == "__main__": - main() diff --git a/tools/build_wave_reverse.py b/tools/build_wave_reverse.py deleted file mode 100644 index 51720b3..0000000 --- a/tools/build_wave_reverse.py +++ /dev/null @@ -1,118 +0,0 @@ -#!/usr/bin/env python3 -# SPDX-License-Identifier: MPL-2.0 -"""Explicitly build the opt-in Wave reverse archive from an immutable source tree. - -Ordinary Cargo builds never run this bootstrap or download a compiler. The input -repository is read only: git archive reads the pinned committed tree, regardless -of unrelated working-tree changes. The temporary source archive contains no Git -checkout or private/untracked files, and supplies its immutable std revision. -""" -import argparse -import hashlib -import io -import json -import os -from pathlib import Path -import subprocess -import tarfile -import tempfile - -WAVE_REVISION = "e0952ed65d07e14c6ed0aa64f3c9a5532dd7533b" -ABI_VERSION = 1 -METADATA_NAME = "reverse-core.meta" - - -def fnv64(data): - """Compatibility fingerprint, not a cryptographic trust check.""" - value = 0xcbf29ce484222325 - for byte in data: - value = ((value ^ byte) * 0x100000001b3) & 0xffffffffffffffff - return f"{value:016x}" - - -def fingerprint_metadata(source, archive): - return (f"schema=1\nabi_version={ABI_VERSION}\n" - f"source_fnv64={fnv64(source)}\narchive_fnv64={fnv64(archive)}\n") - - -def run(arguments, **kwargs): - subprocess.run(list(map(str, arguments)), check=True, **kwargs) - - -def digest(path): - return hashlib.sha256(path.read_bytes()).hexdigest() - - -def main(): - parser = argparse.ArgumentParser(description=__doc__) - parser.add_argument("--wave-source", required=True, type=Path, - help="Wave Git repository containing the official pinned commit; never modified") - parser.add_argument("--out-dir", required=True, type=Path) - parser.add_argument("--rust-toolchain", default="1.89.0") - parser.add_argument("--opt-level", choices=["0", "2"], default="2") - parser.add_argument("--allow-network", action="store_true", - help="explicitly permit Cargo dependency downloads during this bootstrap") - args = parser.parse_args() - repository = args.wave_source.resolve() - revision = subprocess.check_output( - ["git", "-C", str(repository), "rev-parse", WAVE_REVISION + "^{commit}"], text=True).strip() - if revision != WAVE_REVISION: - parser.error("Wave repository does not contain the pinned immutable commit") - rustc = subprocess.check_output(["rustc", "+" + args.rust_toolchain, "--version"], text=True).strip() - if not rustc.startswith("rustc 1.89.0 "): - parser.error("the pinned Wave compiler requires Rust 1.89.0") - output = args.out_dir.resolve() - output.mkdir(parents=True, exist_ok=True) - root = Path(__file__).resolve().parents[1] - kernels = [root / "reverse/wave/amd64.wave", root / "reverse/wave/cfg.wave"] - kernel_contents = [path.read_bytes() for path in kernels] - kernel_bytes = b"\n".join(kernel_contents) - environment = os.environ.copy() - environment["WAVE_STD_REVISION"] = WAVE_REVISION - environment["CARGO_INCREMENTAL"] = "0" - # Neither the mutable checkout nor an installed wavec supplies compiler/std. - archive = subprocess.check_output(["git", "-C", str(repository), "archive", "--format=tar", WAVE_REVISION]) - with tempfile.TemporaryDirectory(prefix=".wave-reverse-", dir=output) as temporary: - temporary = Path(temporary) - source = temporary / "source" - source.mkdir() - with tarfile.open(fileobj=io.BytesIO(archive)) as tree: - tree.extractall(source, filter="data") - command = ["cargo", "+" + args.rust_toolchain, "build", "--locked", "--jobs", "2", - "--manifest-path", source / "Cargo.toml", "--target-dir", output / "bootstrap", "--bin", "wavec"] - if not args.allow_network: - command.append("--offline") - run(command, cwd=source, env=environment) - compiler = output / "bootstrap/debug/wavec" - # A single compilation unit lets the CFG call the same Wave decoder. - kernel = temporary / "reverse.wave" - kernel.write_bytes(kernel_bytes) - obj = temporary / "reverse.o" - run([compiler, "-O" + args.opt_level, "-C", "relocation-model=pic", "--std-root", source / "std", - "--target=x86_64-unknown-linux-gnu", "build", kernel, "--freestanding", - "--emit=obj", "-o", obj, "--target-dir", temporary / "wave-build"], cwd=temporary) - candidate = temporary / "libwhale_wave_reverse.a" - run([environment.get("AR", "ar"), "crsD", candidate, obj]) - provenance = { - "abi_version": ABI_VERSION, "wave_revision": WAVE_REVISION, - "backend": "wave-llvm-bootstrap", "host": "x86_64-unknown-linux-gnu", - "rustc": rustc, "opt_level": args.opt_level, - "compiler_sha256": digest(compiler), "archive_sha256": digest(candidate), - "kernels": {str(path.relative_to(root)): hashlib.sha256(content).hexdigest() - for path, content in zip(kernels, kernel_contents)}, - } - # Prepare every publication file before touching the last-good set. - # Each rename is atomic. An interruption between renames is rejected by - # the fingerprint guard rather than silently linking mixed generations. - metadata = temporary / "provenance.json" - metadata.write_text(json.dumps(provenance, indent=2) + "\n") - fingerprint = temporary / METADATA_NAME - fingerprint.write_text(fingerprint_metadata(kernel_bytes, candidate.read_bytes())) - os.replace(candidate, output / candidate.name) - os.replace(metadata, output / metadata.name) - os.replace(fingerprint, output / fingerprint.name) - print(f"WHALE_WAVE_REVERSE_DIR={output}") - - -if __name__ == "__main__": - main() diff --git a/tools/check_asmobj.py b/tools/check_asmobj.py new file mode 100644 index 0000000..de78f60 --- /dev/null +++ b/tools/check_asmobj.py @@ -0,0 +1,337 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: MPL-2.0 +"""Compare the compiled asmobj source module with an independent Python oracle. + +Build the five explicit Wave sources with the pinned helper, link its object as +a shared library, then pass --library. No Rust asmobj implementation is involved. +""" +from __future__ import annotations + +import argparse +import ctypes as c +import itertools +import json +from pathlib import Path +import random + +U64 = c.c_uint64 +U8P = c.POINTER(c.c_uint8) +NONE = (1 << 64) - 1 + + +class Target(c.Structure): + _fields_ = [(name, U64) for name in ("format", "machine", "address_bits", "endian")] + + +class Section(c.Structure): + _fields_ = [("name", U8P), ("name_len", U64), ("kind", U64), ("alignment", U64), + ("data", U8P), ("data_len", U64), ("zero_fill", U64)] + + +class Symbol(c.Structure): + _fields_ = [("name", U8P), ("name_len", U64), ("kind", U64), ("section", U64), + ("offset", U64), ("size", U64), ("binding", U64), ("visibility", U64)] + + +class Relocation(c.Structure): + _fields_ = [("section", U64), ("offset", U64), ("name", U8P), ("name_len", U64), + ("kind", U64), ("namespace", U8P), ("namespace_len", U64), + ("code", U64), ("addend", c.c_int64)] + + +class Result(c.Structure): + _fields_ = [(name, U64) for name in ("status", "index", "symbol_count")] + + +class Fixture: + def __init__(self, target=(0, 0, 64, 0)): + self.target = target + self.sections = [] + self.symbols = [] + self.relocations = [] + + def section(self, kind=0, name=b".text", alignment=16, data=b"\x90" * 16, zero=0): + self.sections.append((name, kind, alignment, data, zero)) + return self + + def symbol(self, name=b"entry", section=0, kind=0, offset=0, size=0, binding=0, visibility=0): + self.symbols.append((name, kind, section, offset, size, binding, visibility)) + return self + + def relocation(self, name=b"entry", kind=4, namespace=b"", code=0, section=0, + offset=0, addend=-4): + self.relocations.append((section, offset, name, kind, namespace, code, addend)) + return self + + +def oracle(fixture): + fmt, machine, bits, endian = fixture.target + if fmt > 2 or machine > 3 or bits != 64 or endian != 0 or (fmt != 0 and machine > 1): + return 1, 0, None + sections = [(name, (0, 1, 3, 2)[kind], align, data, zero) + for name, kind, align, data, zero in fixture.sections] + for index, symbol in enumerate(fixture.symbols): + if symbol[2] != NONE and symbol[2] >= len(sections): + return 2, index, None + undefined = {symbol[0]: symbol[2] == NONE for symbol in fixture.symbols} + known = set(undefined) + symbols = list(fixture.symbols) + relocations = [] + for index, (section, offset, name, kind, namespace, code, addend) in enumerate(fixture.relocations): + result_code = 0 + if kind == 6: + owner = {b"aarch64": 1, b"riscv64": 2, b"loongarch64": 3}.get(namespace) + if owner is None: + return 3, index, None + if owner != machine: + return 4, index, None + if fmt == 0: + result_code = code + elif fmt == 2 and owner == 1 and code in (282, 283): + kind, result_code = 8, 2 + elif fmt == 1 and owner == 1: + codes = {274: 5, 280: 15, 282: 3, 283: 3} + if code not in codes: + return 5, index, None + kind, result_code = 7, codes[code] + else: + return 6, index, None + elif kind == 4: + if fmt == 2: + kind, result_code = 8, 2 + elif not undefined.get(name, True): + kind = 3 + relocations.append((section, offset, name, kind, b"", result_code, addend)) + if name not in known: + known.add(name) + symbols.append((name, 0, NONE, 0, 0, 1, 0)) + return 0, 0, (sections, symbols, relocations) + + +def raw_bytes(value): + return c.string_at(c.addressof(value), c.sizeof(value)) + + +class Checker: + def __init__(self, library): + self.library = c.CDLL(str(Path(library).resolve())) + self.entry = self.library.whale_asmobj + self.entry.argtypes = [c.POINTER(Target), c.POINTER(Section), U64, c.POINTER(Symbol), U64, + c.POINTER(Relocation), U64, c.POINTER(Section), U64, + c.POINTER(Symbol), U64, c.POINTER(Relocation), U64, + c.POINTER(U64), U64, c.POINTER(Result)] + self.entry.restype = c.c_int32 + self.count = 0 + + def check(self, fixture, capacity=None, expected_status=None, mutate=None): + keep = [] + + def span(data): + storage = (c.c_uint8 * max(1, len(data)))() + if data: + c.memmove(storage, data, len(data)) + keep.append(storage) + return c.cast(storage, U8P), len(data) + + target = Target(*fixture.target) + sections = (Section * len(fixture.sections))() + for i, (name, kind, align, data, zero) in enumerate(fixture.sections): + name_ptr, name_len = span(name) + data_ptr, data_len = span(data) + sections[i] = Section(name_ptr, name_len, kind, align, data_ptr, data_len, zero) + symbols = (Symbol * len(fixture.symbols))() + for i, (name, kind, section, offset, size, binding, visibility) in enumerate(fixture.symbols): + name_ptr, name_len = span(name) + symbols[i] = Symbol(name_ptr, name_len, kind, section, offset, size, binding, visibility) + relocs = (Relocation * len(fixture.relocations))() + for i, (section, offset, name, kind, namespace, code, addend) in enumerate(fixture.relocations): + name_ptr, name_len = span(name) + ns_ptr, ns_len = span(namespace) + relocs[i] = Relocation(section, offset, name_ptr, name_len, kind, ns_ptr, ns_len, code, addend) + expected, index, converted = oracle(fixture) + ns, ny, nr = len(sections), len(symbols) + len(relocs), len(relocs) + out_sections = (Section * max(1, ns))() + out_symbols = (Symbol * max(1, ny))() + out_relocs = (Relocation * max(1, nr))() + for output in (out_sections, out_symbols, out_relocs): + c.memset(c.addressof(output), 0xA5, c.sizeof(output)) + before_outputs = tuple(raw_bytes(v) for v in (out_sections, out_symbols, out_relocs)) + before_inputs = tuple(raw_bytes(v) for v in (target, sections, symbols, relocs)) + total = len(symbols) + len(relocs) + words = 8 * (1 << (total - 1).bit_length()) if total else 0 + scratch = (U64 * max(1, words))() + result = Result(99, 99, 99) + capacities = list(capacity or (ns, ny, nr)) + call = [c.byref(target), sections, ns, symbols, len(symbols), relocs, nr, + out_sections, capacities[0], out_symbols, capacities[1], out_relocs, + capacities[2], scratch, words, c.byref(result)] + if mutate: + mutate(call, sections, symbols, relocs, scratch) + before_inputs = tuple(raw_bytes(v) for v in (target, sections, symbols, relocs)) + status = self.entry(*call) + expected = expected if expected_status is None else expected_status + assert status == expected and result.status == status, (fixture.__dict__, status, expected, result.status) + assert tuple(raw_bytes(v) for v in (target, sections, symbols, relocs)) == before_inputs + if status: + assert result.symbol_count == 0 + if expected_status is None: + assert result.index == index, (status, result.index, index) + assert tuple(raw_bytes(v) for v in (out_sections, out_symbols, out_relocs)) == before_outputs + else: + assert result.index == 0 and result.symbol_count == len(converted[1]) + + def data(ptr, length): + return c.string_at(ptr, length) + + actual_sections = [(data(v.name, v.name_len), v.kind, v.alignment, + data(v.data, v.data_len), v.zero_fill) for v in out_sections[:ns]] + actual_symbols = [(data(v.name, v.name_len), v.kind, v.section, v.offset, v.size, + v.binding, v.visibility) for v in out_symbols[:result.symbol_count]] + actual_relocs = [(v.section, v.offset, data(v.name, v.name_len), v.kind, + data(v.namespace, v.namespace_len), v.code, v.addend) + for v in out_relocs[:nr]] + assert (actual_sections, actual_symbols, actual_relocs) == converted + # Spare rows are never published or overwritten. + tail = result.symbol_count * c.sizeof(Symbol) + assert raw_bytes(out_symbols)[tail:] == before_outputs[1][tail:] + self.count += 1 + + def check_emission_work_budget(self, length, repetitions, expected): + # Keep the independent near-budget regression outside oracle(): a large + # diagnostic must never stringify a 24 MiB fixture or Python-hash it. + # The old preflight omitted equality when an empty slot became occupied. + name = (c.c_uint8 * length)() + c.memset(name, ord("a"), length) + section_name = (c.c_uint8 * 5)(*b".text") + sections = (Section * 1)(Section(section_name, 5, 0, 1, None, 0, 0)) + symbols = (Symbol * 0)() + relocs = (Relocation * repetitions)(*[ + Relocation(0, 0, name, length, 4, None, 0, 0, -4) + for _ in range(repetitions)]) + out_sections = (Section * 1)() + out_symbols = (Symbol * repetitions)() + out_relocs = (Relocation * repetitions)() + outputs = (out_sections, out_symbols, out_relocs) + for output in outputs: + c.memset(c.addressof(output), 0xA5, c.sizeof(output)) + before = tuple(raw_bytes(v) for v in outputs) + target = Target(0, 0, 64, 0) + words = 8 * (1 << (repetitions - 1).bit_length()) + scratch = (U64 * words)() + result = Result(99, 99, 99) + status = self.entry(c.byref(target), sections, 1, symbols, 0, relocs, repetitions, + out_sections, 1, out_symbols, repetitions, out_relocs, + repetitions, scratch, words, c.byref(result)) + assert status == expected and result.status == expected, (length, repetitions, status, result.status) + if expected: + assert result.symbol_count == 0 + assert tuple(raw_bytes(v) for v in outputs) == before + else: + assert result.symbol_count == 1 + assert out_symbols[0].section == NONE and out_symbols[0].name_len == length + assert out_symbols[0].binding == 1 and out_symbols[0].kind == 0 + assert c.cast(out_symbols[0].name, c.c_void_p).value == c.addressof(name) + for relocation in out_relocs: + assert relocation.kind == 4 and relocation.name_len == length and relocation.addend == -4 + assert raw_bytes(out_symbols)[c.sizeof(Symbol):] == before[1][c.sizeof(Symbol):] + # Read the borrowed input through a bounded C comparison, with no Python + # per-byte loop or large temporary expansion. + expected_name = b"a" * length + assert c.string_at(name, length) == expected_name + self.count += 1 + + +def run(checker, cases): + checker.check(Fixture()) + for fmt, machine in itertools.product(range(4), range(5)): + for state in ("unknown", "undefined", "defined", "duplicate"): + fixture = Fixture((fmt, machine, 64, 0)).section() + if state == "undefined": + fixture.symbol(section=NONE) + elif state == "defined": + fixture.symbol() + elif state == "duplicate": + fixture.symbol().symbol(section=NONE) + for kind in range(6): + fixture.relocation(kind=kind) + checker.check(fixture) + for fmt, machine, namespace, code in itertools.product( + range(3), range(4), (b"aarch64", b"riscv64", b"loongarch64", b"unknown", b""), + (0, 16, 17, 64, 66, 274, 280, 282, 283, (1 << 32) - 1)): + checker.check(Fixture((fmt, machine, 64, 0)).section().relocation( + kind=6, namespace=namespace, code=code)) + checker.check(Fixture().section(kind=2).section(kind=3, data=b"", zero=1 << 40) + .symbol(b"\xce\xbb", section=1, kind=2, size=1 << 40, binding=1, visibility=1) + .relocation(name=b"missing").relocation(name=b"missing") + .relocation(name=b"second", kind=0, addend=-(1 << 63))) + checker.check(Fixture().section().symbol(section=999)) + for slot in range(3): + capacities = [1, 1, 1] + capacities[slot] = 0 + checker.check(Fixture().section().relocation(), capacity=capacities, expected_status=7) + checker.check(Fixture().section().relocation(), expected_status=8, + mutate=lambda call, *_: call.__setitem__(7, None)) + checker.check(Fixture().section().relocation(), expected_status=7, + mutate=lambda call, *_: call.__setitem__(14, 4)) + checker.check(Fixture().section().relocation(), expected_status=8, + mutate=lambda call, sections, symbols, relocs, _: setattr(relocs[0], "kind", 99)) + checker.check(Fixture().section().relocation(), expected_status=9, + mutate=lambda call, sections, symbols, relocs, _: setattr(relocs[0], "name_len", 67108865)) + # Deliberate linear-probe collisions exercise retained source indices, + # comparisons, duplicated references and the full-table emission pass. + colliding = [] + candidate = 0 + while len(colliding) < 64: + name = f"collision_{candidate}".encode() + hash_value = 14695981039346656037 + for octet in name: + hash_value = ((hash_value ^ octet) * 1099511628211) & NONE + if hash_value & 255 == 0: + colliding.append(name) + candidate += 1 + collisions = Fixture().section() + for name in colliding[:32]: + collisions.symbol(name) + for name in colliding: + collisions.relocation(name) + for name in colliding[32:]: + collisions.relocation(name) + checker.check(collisions) + checker.check_emission_work_budget(16 * 1024 * 1024 - 64, 1, 0) + checker.check_emission_work_budget(16 * 1024 * 1024, 1, 9) + checker.check_emission_work_budget(24 * 1024 * 1024, 1, 9) + checker.check_emission_work_budget(7 * 1024 * 1024, 2, 0) + checker.check_emission_work_budget(8 * 1024 * 1024, 2, 9) + rng = random.Random(0xA5_0B1_EC7) + names = [b"entry", b"x", b"", b"long_name" * 20, b"\xce\xbb", b"a\0b"] + for _ in range(cases): + fixture = Fixture((rng.randrange(3), rng.randrange(4), 64, 0)) + for _ in range(rng.randrange(1, 5)): + fixture.section(rng.randrange(4), rng.choice(names), 1 << rng.randrange(5), + bytes(rng.randrange(256) for _ in range(rng.randrange(20))), rng.randrange(100)) + for _ in range(rng.randrange(10)): + fixture.symbol(rng.choice(names), rng.choice((NONE, rng.randrange(len(fixture.sections)))), + rng.randrange(3), rng.randrange(50), rng.randrange(50), rng.randrange(2), rng.randrange(2)) + for _ in range(rng.randrange(15)): + fixture.relocation(rng.choice(names), rng.randrange(7), + rng.choice((b"aarch64", b"riscv64", b"loongarch64", b"wrong")), + rng.choice((0, 16, 17, 64, 65, 66, 274, 280, 282, 283)), + rng.randrange(len(fixture.sections)), rng.randrange(20), rng.randrange(-100, 100)) + checker.check(fixture) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--library", required=True, type=Path) + parser.add_argument("--cases", type=int, default=10000) + args = parser.parse_args() + if args.cases < 0: + parser.error("--cases must be nonnegative") + assert [c.sizeof(t) for t in (Target, Section, Symbol, Relocation, Result)] == [32, 56, 64, 72, 24] + checker = Checker(args.library) + run(checker, args.cases) + print(json.dumps({"library": str(args.library), "cases": checker.count, "status": "passed"})) + + +if __name__ == "__main__": + main() diff --git a/tools/check_module_layers.py b/tools/check_module_layers.py new file mode 100644 index 0000000..103cd14 --- /dev/null +++ b/tools/check_module_layers.py @@ -0,0 +1,78 @@ +"""Check local production dependency direction without compiling a product. + +Dev-dependencies are deliberately excluded: an independent test oracle may use +an ISA. Optional and target-conditional production dependencies are still checked. +""" + +import argparse +import json +from pathlib import Path +import tomllib + + +ROOT = Path(__file__).resolve().parents[1] +CORE = { + "diagnostic": set(), + "target-spec": set(), + "assembler": {"target-spec", "diagnostic"}, + "ir": {"target-spec", "diagnostic"}, + "backend-api": {"ir", "target-spec", "diagnostic"}, + "object": {"target-spec", "diagnostic"}, + "linker": {"object", "diagnostic"}, + "reverse": {"object"}, + "toolchain": {"assembler", "backend-api", "ir", "target-spec", "diagnostic", "object"}, +} + + +def production_dependencies(manifest): + for section in ("dependencies", "build-dependencies"): + yield from manifest.get(section, {}).values() + for conditional in manifest.get("target", {}).values(): + yield from production_dependencies(conditional) + + +def audit(root=ROOT): + root = Path(root).resolve() + workspace = tomllib.loads((root / "Cargo.toml").read_text()) + members = set(workspace["workspace"]["members"]) | {"."} + packages = {} + for member in sorted(members): + location = (root / member).resolve() + manifest = tomllib.loads((location / "Cargo.toml").read_text()) + name = manifest["package"]["name"] + if name in packages: + raise ValueError(f"duplicate package {name}") + packages[name] = (location, manifest) + names = {location: name for name, (location, _) in packages.items()} + edges = {} + for name, (location, manifest) in sorted(packages.items()): + dependencies = set() + for dep in production_dependencies(manifest): + if isinstance(dep, dict) and "path" in dep: + path = (location / dep["path"]).resolve() + if path not in names: + raise ValueError(f"{name}: unclassified local dependency {path}") + dependencies.add(names[path]) + edges[name] = sorted(dependencies) + if name in CORE: + forbidden = dependencies - CORE[name] + if forbidden: + raise ValueError(f"{name}: forbidden production dependency {sorted(forbidden)}") + missing = CORE.keys() - packages.keys() + if missing: + raise ValueError(f"missing core packages: {sorted(missing)}") + return {"schema": 1, "production_dependencies": edges} + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--root", type=Path, default=ROOT) + args = parser.parse_args() + try: + print(json.dumps(audit(args.root), sort_keys=True, indent=2)) + except (ValueError, OSError) as error: + parser.exit(1, f"module layers: {error}\n") + + +if __name__ == "__main__": + main() diff --git a/tools/meson_cargo.py b/tools/meson_cargo.py new file mode 100644 index 0000000..16a6539 --- /dev/null +++ b/tools/meson_cargo.py @@ -0,0 +1,313 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: MPL-2.0 +"""Internal Meson bridge for existing Rust components; never used at configure. + +Cargo's target triple selects where the Whale executable runs. The independent +asm-* features select which machine-code outputs that executable can produce. +""" + +import argparse +import json +import os +from pathlib import Path +import re +import shutil +import subprocess +import tempfile + + +class BuildError(ValueError): + pass + + +ASSEMBLERS = ("amd64", "aarch64", "riscv64", "loongarch64") +FEATURES = {"asm-" + arch for arch in ASSEMBLERS} | {"socket-cli"} +COMPONENTS = ("diagnostic", "assembler", "backend-api", "toolchain", + "reverse", "target-spec", "object", "linker", "ir") +TRIPLE = re.compile(r"[A-Za-z0-9][A-Za-z0-9_-]+\Z") + + +def validate_features(features): + features = sorted(set(features)) + unknown = set(features) - FEATURES + if unknown: + raise BuildError("unknown product feature: " + min(unknown)) + return features + + +def cargo_environment(target_dir, asmobj_directory, profile, optimization, debug_info): + environment = os.environ.copy() + environment.pop("WHALE_ASMOBJ_DIR", None) + environment.pop("CARGO_BUILD_TARGET", None) + environment["CARGO_TARGET_DIR"] = str(target_dir) + environment["CARGO_INCREMENTAL"] = "0" + prefix = "CARGO_PROFILE_" + profile.upper() + "_" + environment[prefix + "OPT_LEVEL"] = optimization + environment[prefix + "DEBUG"] = debug_info + if asmobj_directory: + environment["WHALE_ASMOBJ_DIR"] = str(asmobj_directory) + return environment + + +def native_target(cargo, source, environment): + result = subprocess.run([str(cargo), "-vV"], cwd=source, env=environment, check=True, + capture_output=True, text=True) + targets = [line.removeprefix("host: ") for line in result.stdout.splitlines() if line.startswith("host: ")] + if len(targets) != 1 or not TRIPLE.fullmatch(targets[0]): + raise BuildError("Cargo did not report one native host triple") + return targets[0] + + +def cargo_command(cargo, source, target_dir, target, profile, features, offline, jobs): + command = [str(cargo), "build", "--locked", "--manifest-path", str(source / "Cargo.toml"), + "--target-dir", str(target_dir), "--target", target, "--profile", profile, + "--jobs", str(jobs), "-p", "whale", "--bin", "whale", "--no-default-features"] + if offline: + command.append("--offline") + if features: + command.extend(["--features", ",".join(features)]) + return command + + +def validate_host(rustc, target, system, cpu_family, source, environment): + result = subprocess.run([str(environment.get("RUSTC", rustc)), "--print", "cfg", "--target", target], + cwd=source, env=environment, check=True, capture_output=True, text=True) + values = {} + for line in result.stdout.splitlines(): + if line.startswith(('target_arch="', 'target_os="')) and line.endswith('"'): + name, value = line.split("=", 1) + values[name] = value[1:-1] + expected_os = {"darwin": "macos"}.get(system, system) + expected_arch = {"ppc": "powerpc", "ppc64": "powerpc64"}.get(cpu_family, cpu_family) + if values != {"target_os": expected_os, "target_arch": expected_arch}: + raise BuildError(f"Rust host target {target!r} disagrees with Meson host {system}/{cpu_family}; " + "use the matching Meson cross file and cargo-host-target") + + +def make_escape(path): + return str(path).replace("\\", "\\\\").replace("$", "$$").replace(" ", "\\ ").replace("#", "\\#").replace(":", "\\:") + + +def cargo_dependencies(path): + """Read the first Make dependency rule, including escaped path spaces.""" + text = Path(path).read_text(encoding="utf-8").replace("\\\n", "") + line = text.splitlines()[0] if text else "" + start = None + for index, character in enumerate(line): + if character == ":" and (index + 1 == len(line) or line[index + 1].isspace()): + backslashes = 0 + previous = index - 1 + while previous >= 0 and line[previous] == "\\": + backslashes += 1 + previous -= 1 + if backslashes % 2 == 0: + start = index + 1 + break + if start is None: + raise BuildError("Cargo produced a malformed binary dependency file") + result = [] + token = [] + index = start + while index < len(line): + character = line[index] + if character == "\\" and index + 1 < len(line) and line[index + 1] in " \\#:": + index += 1 + token.append(line[index]) + elif character == "$" and index + 1 < len(line) and line[index + 1] == "$": + index += 1 + token.append("$") + elif character.isspace(): + if token: + result.append("".join(token)) + token = [] + else: + token.append(character) + index += 1 + if token: + result.append("".join(token)) + return result + + +def source_dependencies(source, features): + """Explicit source-tree components, with directories tracking new files.""" + dependencies = {source, source / "Cargo.toml", source / "Cargo.lock", Path(__file__).resolve()} + components = [*COMPONENTS, *("assembler/" + arch for arch in ASSEMBLERS if "asm-" + arch in features)] + for component in ["", *components]: + root = source / component + for name in ["Cargo.toml", "build.rs"]: + if (root / name).is_file(): + dependencies.add(root / name) + tree = root / "src" + if tree.is_dir(): + for directory, _, files in os.walk(tree, followlinks=False): + directory = Path(directory) + dependencies.add(directory) + dependencies.update(directory / name for name in files) + for path in [source / ".cargo", source / "rust-toolchain", source / "rust-toolchain.toml"]: + if path.is_file(): + dependencies.add(path) + elif path.is_dir(): + dependencies.add(path) + dependencies.update(path.iterdir()) + dependencies.add(source / "assembler/asmobj") + dependencies.update((source / "assembler/asmobj").glob("*.wave")) + return dependencies + + +def _temporary_copy(source, destination): + with tempfile.NamedTemporaryFile(prefix=".whale-", dir=destination.parent, delete=False) as temporary: + path = Path(temporary.name) + try: + # Preserve executability, but publish a fresh mtime even when Cargo + # reused its binary after a build-rule/directory dependency changed. + shutil.copyfile(source, path) + shutil.copymode(source, path) + return path + except BaseException: + path.unlink(missing_ok=True) + raise + + +def build(arguments): + source = arguments.source_root.resolve() + target_dir = arguments.target_dir.resolve() + # Atomic replacement replaces the output entry itself, including an old + # symlink, rather than following it into an unrelated source file. + output = arguments.output.parent.resolve() / arguments.output.name + depfile = arguments.depfile.parent.resolve() / arguments.depfile.name + asmobj_directory = arguments.asmobj_dir.resolve() if arguments.asmobj_dir else None + features = validate_features(arguments.feature) + if target_dir in [source, source / "target"]: + raise BuildError("Meson requires its own private Cargo target directory") + environment = cargo_environment(target_dir, asmobj_directory, arguments.profile, + arguments.opt_level, arguments.debug_info) + target = arguments.host_target or native_target(arguments.cargo, source, environment) + if not TRIPLE.fullmatch(target): + raise BuildError("cargo host target must be a Rust target triple") + validate_host(arguments.rustc, target, arguments.host_system, arguments.host_cpu_family, source, environment) + subprocess.run(cargo_command(arguments.cargo, source, target_dir, target, arguments.profile, + features, arguments.offline, arguments.jobs), cwd=source, + env=environment, check=True) + directory = target_dir / target / ("debug" if arguments.profile == "dev" else "release") + binary = directory / ("whale.exe" if arguments.host_system == "windows" else "whale") + if not binary.is_file(): + raise BuildError("Cargo did not produce the requested Whale host executable") + dependencies = source_dependencies(source, features) + dependencies.update(Path(path) if Path(path).is_absolute() else source / path + for path in cargo_dependencies(directory / "whale.d")) + if asmobj_directory: + archive = "whale_asmobj.lib" if "msvc" in target else "libwhale_asmobj.a" + dependencies.update(asmobj_directory / name for name in [archive, "asmobj.meta"]) + contents = make_escape(output) + ": " + " ".join(make_escape(path) for path in sorted(dependencies)) + "\n" + candidate = None + candidate_depfile = None + try: + candidate = _temporary_copy(binary, output) + with tempfile.NamedTemporaryFile(prefix=".whale-deps-", dir=depfile.parent, delete=False) as temporary: + candidate_depfile = Path(temporary.name) + temporary.write(contents.encode("utf-8")) + # Prepare both before publishing. Dependency output failure cannot + # replace the last-good executable. + os.replace(candidate_depfile, depfile) + os.replace(candidate, output) + finally: + if candidate is not None: + candidate.unlink(missing_ok=True) + if candidate_depfile is not None: + candidate_depfile.unlink(missing_ok=True) + + +def smoke(arguments): + features = set(arguments.feature) + binary = arguments.binary.resolve(strict=True) + launcher = [*arguments.runner_arg, str(binary)] + with tempfile.TemporaryDirectory(prefix="whale-meson-smoke-") as temporary: + directory = Path(temporary) + + def invoke(values): + return subprocess.run([*launcher, *map(str, values)], cwd=directory, capture_output=True, timeout=20) + + version = invoke(["--version"]) + if version.returncode or not version.stdout.startswith(b"whale "): + raise BuildError("Whale host version smoke failed") + probe = invoke(["asm", "--arch", "meson-unregistered-probe", "missing.s", "-o", "probe.o"]) + expected = ", ".join(sorted(arch for arch in ASSEMBLERS if "asm-" + arch in features)).encode() + if probe.returncode == 0 or b"unregistered assembler" not in probe.stderr or b"available: " + expected + b"\n" not in probe.stderr: + raise BuildError("Whale assembler selection differs from the Meson product") + if (directory / "probe.o").exists(): + raise BuildError("selection probe unexpectedly published output") + ir = directory / "answer.wir" + ir.write_text('module {\n format_version 8\n semantics_version 1\n target "x86_64-whale-linux"\n' + ' datalayout { ptr=64, endian=little }\n declare @f0 "answer": whale () -> i32, linkage internal\n' + ' fn @f0 "answer"() -> i32, entry %b0 {\n %b0 "entry":\n %v0: i32 = const i32 42\n' + ' ret i32 %v0\n }\n}\n', encoding="utf-8") + result = invoke(["ir", "run", ir, "--function", "@f0"]) + if result.returncode or result.stdout != b"i32 42\n": + raise BuildError("Whale IR smoke failed") + + +def bootstrap(arguments): + from wave_bootstrap import BootstrapError, ensure_bootstrap + try: + result = ensure_bootstrap(arguments.wave_source, arguments.cache_dir, + rust_toolchain=arguments.rust_toolchain, + allow_network=arguments.allow_network) + except BootstrapError as error: + raise BuildError(str(error)) from error + output = arguments.output.resolve() + candidate = None + try: + with tempfile.NamedTemporaryFile(prefix=".wave-ready-", dir=output.parent, delete=False) as temporary: + candidate = Path(temporary.name) + temporary.write((json.dumps(result.paths(), sort_keys=True) + "\n").encode("utf-8")) + os.replace(candidate, output) + finally: + if candidate is not None: + candidate.unlink(missing_ok=True) + + +def main(argv=None): + parser = argparse.ArgumentParser(description=__doc__) + commands = parser.add_subparsers(dest="command", required=True) + compile_parser = commands.add_parser("build") + compile_parser.add_argument("--cargo", required=True) + compile_parser.add_argument("--rustc", required=True) + for name in ["source-root", "target-dir", "output", "depfile"]: + compile_parser.add_argument("--" + name, type=Path, required=True) + compile_parser.add_argument("--host-target", default="") + compile_parser.add_argument("--host-system", required=True) + compile_parser.add_argument("--host-cpu-family", required=True) + compile_parser.add_argument("--profile", choices=["dev", "release"], required=True) + compile_parser.add_argument("--opt-level", choices=["0", "1", "2", "3", "s", "z"], required=True) + compile_parser.add_argument("--debug-info", choices=["0", "2"], required=True) + compile_parser.add_argument("--jobs", type=int, default=2) + compile_parser.add_argument("--offline", action="store_true") + compile_parser.add_argument("--feature", action="append", default=[]) + compile_parser.add_argument("--asmobj-dir", type=Path) + smoke_parser = commands.add_parser("smoke") + smoke_parser.add_argument("--binary", type=Path, required=True) + smoke_parser.add_argument("--feature", action="append", default=[]) + smoke_parser.add_argument("--runner-arg", action="append", default=[]) + bootstrap_parser = commands.add_parser("bootstrap") + bootstrap_parser.add_argument("--wave-source", type=Path, required=True) + bootstrap_parser.add_argument("--cache-dir", type=Path, required=True) + bootstrap_parser.add_argument("--rust-toolchain", required=True) + bootstrap_parser.add_argument("--output", type=Path, required=True) + bootstrap_parser.add_argument("--allow-network", action="store_true") + arguments = parser.parse_args(argv) + try: + if arguments.command == "build": + if arguments.jobs < 1: + raise BuildError("Cargo jobs must be positive") + build(arguments) + elif arguments.command == "smoke": + smoke(arguments) + else: + bootstrap(arguments) + except (BuildError, OSError, subprocess.SubprocessError) as error: + parser.exit(1, f"Meson Cargo bridge: {error}\n") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tools/test_build_asmobj.py b/tools/test_build_asmobj.py new file mode 100644 index 0000000..1fbaf4c --- /dev/null +++ b/tools/test_build_asmobj.py @@ -0,0 +1,361 @@ +# SPDX-License-Identifier: MPL-2.0 +"""Regress complete asmobj publication and its real std-only Cargo build guard.""" +import contextlib +import hashlib +import io +import json +import os +from pathlib import Path +import shutil +import subprocess +import sys +import tempfile +import unittest +from unittest.mock import patch + +import build_asmobj as helper +from wave_bootstrap import Bootstrap + +ROOT = Path(__file__).resolve().parents[1] +NATIVE = "x86_64-unknown-linux-gnu" + + +class PublicationTests(unittest.TestCase): + def publication(self, *, failure=None, existing=True, target=NATIVE, allow_network=False): + with tempfile.TemporaryDirectory() as temporary: + root = Path(temporary).resolve() + source = root / "Wave" + source.mkdir() + marker = source / "user.wave" + marker.write_bytes(b"unrelated user changes") + output = root / "output" + output.mkdir() + compiler = root / "wavec" + compiler.write_bytes(b"pinned compiler") + std = root / "std" + std.mkdir() + bootstrap = Bootstrap(compiler, std, root / "bootstrap-provenance.json", {"std_sha256": "1" * 64}, True) + archive_name = "whale_asmobj.lib" if "msvc" in target else "libwhale_asmobj.a" + names = (archive_name, "provenance.json", "asmobj.meta") + original = {name: b"previous " + name.encode() for name in names} + if existing: + for name, data in original.items(): + (output / name).write_bytes(data) + calls = [] + + def fake_bootstrap(*args, **kwargs): + self.assertEqual(args, (source, output / "bootstrap-cache")) + self.assertEqual(kwargs, {"rust_toolchain": "1.89", "allow_network": allow_network}) + if failure == "bootstrap": + raise subprocess.CalledProcessError(1, ["cargo"]) + return bootstrap + + def fake_run(command, **kwargs): + command = list(map(str, command)) + calls.append(command) + if "-o" in command: + self.assertEqual(command[0], str(compiler)) + self.assertEqual(command[command.index("--std-root") + 1], str(std)) + self.assertIn("-O0", command) + self.assertIn("relocation-model=pic", command) + self.assertIn("--freestanding", command) + self.assertIn("--emit=obj", command) + wave_target = target.replace("riscv64gc-", "riscv64-") + self.assertIn("--target=" + wave_target, command) + self.assertEqual(kwargs["env"]["WAVE_STD_REVISION"], helper.WAVE_REVISION) + kernel = Path(command[command.index("build") + 1]) + self.assertEqual(kernel.read_bytes(), helper.source_bytes(ROOT)) + self.assertEqual(Path(kwargs["cwd"]), kernel.parent) + Path(command[command.index("-o") + 1]).write_bytes(b"object") + if failure == "compile": + raise subprocess.CalledProcessError(1, command) + else: + expected_archiver = ["asmobj-test-ar"] + if "msvc" in target: + expected_archiver.append("--format=coff") + elif "apple-darwin" in target: + expected_archiver.append("--format=darwin") + expected_archiver.append("crsD") + self.assertEqual(command[:-2], expected_archiver) + self.assertEqual(Path(command[-2]).name, archive_name) + self.assertEqual(Path(command[-1]).read_bytes(), b"object") + Path(command[-2]).write_bytes(b"new archive") + if failure == "archive": + raise subprocess.CalledProcessError(1, command) + + arguments = ["build_asmobj.py", "--wave-source", str(source), "--out-dir", str(output), + "--rust-toolchain", "1.89", "--target", target, "--opt-level", "0"] + if allow_network: + arguments.append("--allow-network") + with patch.object(sys, "argv", arguments), \ + patch.object(helper, "ensure_bootstrap", side_effect=fake_bootstrap), \ + patch.object(helper, "run", side_effect=fake_run), \ + patch.dict(os.environ, {"AR": "asmobj-test-ar"}), \ + contextlib.redirect_stdout(io.StringIO()): + if failure: + with self.assertRaises(subprocess.CalledProcessError): + helper.main() + else: + helper.main() + self.assertEqual(marker.read_bytes(), b"unrelated user changes") + self.assertEqual(sorted(p.name for p in source.iterdir()), ["user.wave"]) + self.assertFalse(any(p.name.startswith(".asmobj-") for p in output.iterdir())) + for name in names: + path = output / name + if failure and existing: + self.assertEqual(path.read_bytes(), original[name]) + elif failure: + self.assertFalse(path.exists(), name) + else: + self.assertTrue(path.is_file(), name) + if not failure: + self.assertEqual(len(calls), 2) + source_bytes = helper.source_bytes(ROOT) + self.assertEqual((output / "asmobj.meta").read_text(), + helper.metadata(source_bytes, b"new archive", target)) + provenance = json.loads((output / "provenance.json").read_text()) + self.assertEqual(provenance, { + "wave_revision": helper.WAVE_REVISION, + "target": target, + "opt_level": "0", + "source_sha256": hashlib.sha256(source_bytes).hexdigest(), + "archive_sha256": hashlib.sha256(b"new archive").hexdigest(), + "compiler_sha256": hashlib.sha256(b"pinned compiler").hexdigest(), + "std_sha256": "1" * 64, + "bootstrap_provenance": str(bootstrap.provenance), + }) + + def test_success_publishes_exact_source_archive_and_compiler_provenance(self): + self.publication() + + def test_compile_archive_and_bootstrap_failures_preserve_last_good_set(self): + for failure in ("bootstrap", "compile", "archive"): + with self.subTest(failure=failure): + self.publication(failure=failure) + + def test_failed_first_build_never_publishes_partial_artifacts(self): + for failure in ("bootstrap", "compile", "archive"): + with self.subTest(failure=failure): + self.publication(failure=failure, existing=False) + + def test_cross_object_targets_keep_distinct_metadata_and_archive_names(self): + for target in ("riscv64gc-unknown-linux-gnu", "aarch64-pc-windows-msvc", "aarch64-apple-darwin"): + with self.subTest(target=target): + self.publication(target=target) + + def test_network_permission_is_explicitly_forwarded(self): + self.publication(allow_network=True) + + def test_output_inside_compiler_checkout_is_rejected_before_bootstrap(self): + with tempfile.TemporaryDirectory() as temporary: + source = Path(temporary).resolve() / "Wave" + source.mkdir() + for output in (source, source / "output"): + with self.subTest(output=output), \ + patch.object(sys, "argv", ["build_asmobj.py", "--wave-source", str(source), + "--out-dir", str(output)]), \ + patch.object(helper, "ensure_bootstrap") as bootstrap, \ + contextlib.redirect_stderr(io.StringIO()): + with self.assertRaises(SystemExit) as error: + helper.main() + self.assertEqual(error.exception.code, 2) + bootstrap.assert_not_called() + self.assertEqual(list(source.iterdir()), []) + + +class BuildGuardTests(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.temporary = tempfile.TemporaryDirectory() + cls.guard = Path(cls.temporary.name).resolve() / ("guard.exe" if os.name == "nt" else "guard") + subprocess.run([shutil.which("rustc") or "rustc", str(ROOT / "toolchain/build.rs"), + "--edition=2021", "-Dwarnings", "-o", str(cls.guard)], + check=True, capture_output=True) + + @classmethod + def tearDownClass(cls): + cls.temporary.cleanup() + + @staticmethod + def make_project(root, target=NATIVE): + manifest = root / "toolchain" + manifest.mkdir() + sources = root / "assembler/asmobj" + sources.mkdir(parents=True) + for index, name in enumerate(helper.SOURCES): + (sources / name).write_bytes(f"source {index}: {name}\n".encode()) + archive_dir = root / "archive" + archive_dir.mkdir() + archive = archive_dir / ("whale_asmobj.lib" if "msvc" in target else "libwhale_asmobj.a") + archive.write_bytes(b"archive") + source_bytes = b"\n".join((sources / name).read_bytes() for name in helper.SOURCES) + metadata = archive_dir / "asmobj.meta" + metadata.write_text(helper.metadata(source_bytes, b"archive", target)) + return manifest, sources, archive_dir, archive, metadata + + def run_guard(self, corruption=None, *, enabled=True, target=NATIVE): + with tempfile.TemporaryDirectory() as temporary: + manifest, sources, archive_dir, archive, metadata = self.make_project(Path(temporary).resolve(), target) + if corruption == "source": + (sources / helper.SOURCES[2]).write_bytes(b"changed source") + elif corruption == "archive": + archive.write_bytes(b"changed archive") + elif corruption == "missing-archive": + archive.unlink() + elif corruption == "missing-source": + (sources / helper.SOURCES[2]).unlink() + elif corruption == "missing-metadata": + metadata.unlink() + elif corruption == "oversized": + metadata.write_text("x" * 4097) + elif corruption == "duplicate": + metadata.write_text(metadata.read_text() + "schema=1\n") + elif corruption == "unknown": + metadata.write_text(metadata.read_text() + "future=1\n") + elif corruption == "incomplete": + metadata.write_text("\n".join(metadata.read_text().splitlines()[:-1]) + "\n") + elif corruption == "malformed": + metadata.write_text(metadata.read_text() + "not an assignment\n") + elif corruption == "invalid-utf8": + metadata.write_bytes(b"\xff") + elif corruption == "schema": + metadata.write_text(metadata.read_text().replace("schema=1", "schema=2")) + elif corruption == "target": + metadata.write_text(metadata.read_text().replace("target=" + target, "target=aarch64-unknown-linux-gnu")) + environment = os.environ.copy() + environment.pop("WHALE_ASMOBJ_DIR", None) + environment.update(CARGO_MANIFEST_DIR=str(manifest), HOST=NATIVE, TARGET=target) + if enabled: + environment["WHALE_ASMOBJ_DIR"] = str(archive_dir) + return subprocess.run([str(self.guard)], env=environment, capture_output=True, text=True) + + def test_matching_guard_watches_all_five_sources_and_published_artifacts(self): + result = self.run_guard() + self.assertEqual(result.returncode, 0, result.stderr) + for name in (*helper.SOURCES, "asmobj.meta", "libwhale_asmobj.a"): + self.assertIn(name, result.stdout) + self.assertIn("cargo:rustc-cfg=whale_asmobj", result.stdout) + self.assertIn("cargo:rustc-link-lib=static=whale_asmobj", result.stdout) + + def test_mismatched_or_invalid_artifacts_fail_before_link_selection(self): + expectations = { + "source": "stale asmobj", "archive": "corrupt asmobj", + "target": "target mismatch", "oversized": "oversized", + "duplicate": "metadata fields", "unknown": "metadata fields", + "incomplete": "incomplete", "malformed": "malformed", + "invalid-utf8": "invalid asmobj metadata", "schema": "unsupported", + "missing-source": "missing asmobj Wave source", + "missing-archive": "missing asmobj archive", + "missing-metadata": "missing asmobj.meta", + } + for corruption, reason in expectations.items(): + with self.subTest(corruption=corruption): + result = self.run_guard(corruption) + self.assertNotEqual(result.returncode, 0, result.stdout) + self.assertIn(reason, result.stderr) + self.assertNotIn("cargo:rustc-link-lib", result.stdout) + self.assertNotIn("cargo:rustc-cfg=whale_asmobj", result.stdout) + + def test_plain_cargo_build_needs_neither_compiler_nor_wave_artifact(self): + result = self.run_guard("missing-metadata", enabled=False) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertNotIn("cargo:rustc-link-lib", result.stdout) + self.assertNotIn("cargo:rustc-cfg=whale_asmobj", result.stdout) + + def test_cross_linked_object_must_match_cargo_target_without_claiming_execution(self): + for target in helper.TARGETS[1:]: + with self.subTest(target=target): + result = self.run_guard(target=target) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertIn("cargo:rustc-cfg=whale_asmobj", result.stdout) + archive = "whale_asmobj.lib" if "msvc" in target else "libwhale_asmobj.a" + self.assertIn(archive, result.stdout) + + def test_cargo_rechecks_warm_source_and_archive_changes(self): + identity = subprocess.check_output([shutil.which("rustc") or "rustc", "-vV"], text=True) + hosts = [line.removeprefix("host: ") for line in identity.splitlines() + if line.startswith("host: ")] + self.assertEqual(len(hosts), 1) + with tempfile.TemporaryDirectory() as temporary: + manifest, sources, archive_dir, archive, metadata = self.make_project(Path(temporary).resolve(), hosts[0]) + (manifest / "src").mkdir() + (manifest / "src/lib.rs").write_text("pub fn marker() {}\n") + (manifest / "Cargo.toml").write_text( + '[package]\nname="asmobj-guard-probe"\nversion="0.0.0"\nedition="2021"\n') + shutil.copyfile(ROOT / "toolchain/build.rs", manifest / "build.rs") + environment = os.environ.copy() + environment.pop("CARGO_BUILD_TARGET", None) + environment.update(WHALE_ASMOBJ_DIR=str(archive_dir), CARGO_TARGET_DIR=str(manifest / "target")) + command = [shutil.which("cargo") or "cargo", "check", "--offline", "--target", hosts[0], + "--manifest-path", str(manifest / "Cargo.toml")] + + def check(success, reason=None): + result = subprocess.run(command, env=environment, capture_output=True, text=True) + self.assertEqual(result.returncode == 0, success, result.stderr) + if reason: + self.assertIn(reason, result.stderr) + + check(True) + source = sources / helper.SOURCES[3] + original = source.read_bytes() + source.write_bytes(original + b"\n") + check(False, "stale asmobj archive") + source.write_bytes(original) + check(True) + archive.write_bytes(b"broken") + check(False, "corrupt asmobj archive") + archive.write_bytes(b"archive") + check(True) + original_metadata = metadata.read_text() + metadata.write_text(original_metadata.replace("schema=1", "schema=2")) + check(False, "unsupported asmobj metadata") + metadata.write_text(original_metadata) + check(True) + + +class SourceStructureTests(unittest.TestCase): + def test_autocrlf_checkout_preserves_wave_source_fingerprint(self): + # Archives are built on Linux and reused by Windows CI. Git must not + # rewrite their source bytes before the Cargo fingerprint guard runs. + with tempfile.TemporaryDirectory() as temporary: + root = Path(temporary).resolve() + sources = root / "assembler/asmobj" + sources.mkdir(parents=True) + shutil.copyfile(ROOT / ".gitattributes", root / ".gitattributes") + for name in helper.SOURCES: + shutil.copyfile(ROOT / "assembler/asmobj" / name, sources / name) + original = helper.source_bytes(root) + environment = {key: value for key, value in os.environ.items() + if not key.startswith("GIT_")} + environment.update(GIT_CONFIG_NOSYSTEM="1", GIT_CONFIG_GLOBAL=os.devnull) + git = shutil.which("git") or "git" + for arguments in (["init", "--quiet"], + ["config", "core.autocrlf", "true"], + ["add", ".gitattributes", "assembler/asmobj"]): + subprocess.run([git, *arguments], cwd=root, env=environment, + check=True, capture_output=True) + for name in helper.SOURCES: + (sources / name).unlink() + subprocess.run([git, "checkout-index", "--all", "--force"], cwd=root, + env=environment, check=True, capture_output=True) + checked_out = helper.source_bytes(root) + self.assertNotIn(b"\r\n", checked_out) + self.assertEqual(checked_out, original) + self.assertEqual(helper.fnv64(checked_out), helper.fnv64(original)) + + def test_asmobj_is_a_complete_wave_module_with_five_role_files(self): + module = ROOT / "assembler/asmobj" + self.assertEqual(sorted(path.name for path in module.glob("*.wave")), sorted(helper.SOURCES)) + self.assertEqual(list(module.rglob("*.rs")), []) + self.assertFalse((module / "Cargo.toml").exists()) + actual = set() + for directory in ("assembler", "object", "reverse", "ir", "toolchain", "src"): + source_root = ROOT / directory + if source_root.is_dir(): + actual.update(path.relative_to(ROOT).as_posix() for path in source_root.rglob("*.wave")) + self.assertFalse(any(path.is_dir() and path.name == "wave" for path in source_root.rglob("*"))) + self.assertEqual(actual, {"assembler/asmobj/" + name for name in helper.SOURCES}) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/test_build_wave_elf.py b/tools/test_build_wave_elf.py deleted file mode 100644 index a25d638..0000000 --- a/tools/test_build_wave_elf.py +++ /dev/null @@ -1,60 +0,0 @@ -"""Test bootstrap publication without installing Wave or LLVM.""" -import contextlib -import io -from pathlib import Path -import subprocess -import sys -import tempfile -import unittest -from unittest.mock import patch - -import build_wave_elf - - -class ArchivePublicationTests(unittest.TestCase): - def run_case(self, fail_archive=False, existing=True): - with tempfile.TemporaryDirectory() as directory: - root = Path(directory) - source = root / "source" - source.mkdir() - out = root / "output" - out.mkdir() - archive = out / "libwhale_wave_elf.a" - if existing: - archive.write_bytes(b"previous good archive") - - def fake_run(command, **kwargs): - if command[0] == "cargo": - return - if "-o" in command: - Path(command[command.index("-o") + 1]).write_bytes(b"object") - return - Path(command[2]).write_bytes(b"new archive") - if fail_archive: - raise subprocess.CalledProcessError(1, command) - - with patch.object(sys, "argv", ["build_wave_elf.py", "--wave-source", str(source), "--out-dir", str(out)]), \ - patch.object(build_wave_elf.subprocess, "check_output", side_effect=[build_wave_elf.WAVE_REVISION, ""]), \ - patch.object(build_wave_elf.subprocess, "run", side_effect=fake_run), \ - contextlib.redirect_stdout(io.StringIO()): - if fail_archive: - with self.assertRaises(subprocess.CalledProcessError): - build_wave_elf.main() - else: - build_wave_elf.main() - if fail_archive and existing: - self.assertEqual(archive.read_bytes(), b"previous good archive") - elif fail_archive: - self.assertFalse(archive.exists()) - else: - self.assertEqual(archive.read_bytes(), b"new archive") - self.assertEqual(set(p.name for p in out.iterdir()), {"elf_records.o", archive.name} if archive.exists() else {"elf_records.o"}) - - def test_failed_archiver_preserves_prior_archive(self): - self.run_case(fail_archive=True) - - def test_failed_archiver_does_not_publish_partial_archive(self): - self.run_case(fail_archive=True, existing=False) - - def test_success_replaces_archive_and_cleans_temporary_files(self): - self.run_case() diff --git a/tools/test_build_wave_reverse.py b/tools/test_build_wave_reverse.py deleted file mode 100644 index fdda67f..0000000 --- a/tools/test_build_wave_reverse.py +++ /dev/null @@ -1,203 +0,0 @@ -"""Exercise publication and the actual std-only Cargo fingerprint guard offline.""" -import contextlib -import io -import os -from pathlib import Path -import shutil -import subprocess -import sys -import tarfile -import tempfile -import unittest -from unittest.mock import patch - -import build_wave_reverse as helper - -ROOT = Path(__file__).resolve().parents[1] - - -class ArchiveTests(unittest.TestCase): - def publication(self, failure=None, existing=True): - with tempfile.TemporaryDirectory() as directory: - root = Path(directory) - source = root / "source" - source.mkdir() - out = root / "output" - out.mkdir() - names = ["libwhale_wave_reverse.a", "provenance.json", helper.METADATA_NAME] - if existing: - for name in names: - (out / name).write_bytes(b"previous " + name.encode()) - tar = io.BytesIO() - with tarfile.open(fileobj=tar, mode="w"): - pass - - def fake_run(command, **kwargs): - if str(command[0]) == "cargo": - compiler = out / "bootstrap/debug/wavec" - compiler.parent.mkdir(parents=True, exist_ok=True) - compiler.write_bytes(b"pinned compiler") - if failure == "bootstrap": - raise subprocess.CalledProcessError(1, command) - elif "-o" in command: - Path(command[command.index("-o") + 1]).write_bytes(b"object") - if failure == "compile": - raise subprocess.CalledProcessError(1, command) - else: - Path(command[2]).write_bytes(b"new archive") - if failure == "archive": - raise subprocess.CalledProcessError(1, command) - - arguments = ["build_wave_reverse.py", "--wave-source", str(source), "--out-dir", str(out)] - with patch.object(sys, "argv", arguments), \ - patch.object(helper.subprocess, "check_output", side_effect=[helper.WAVE_REVISION, "rustc 1.89.0 (test)", tar.getvalue()]), \ - patch.object(helper, "run", side_effect=fake_run), \ - contextlib.redirect_stdout(io.StringIO()): - if failure: - with self.assertRaises(subprocess.CalledProcessError): - helper.main() - else: - helper.main() - for name in names: - path = out / name - if failure and existing: - self.assertEqual(path.read_bytes(), b"previous " + name.encode()) - elif failure: - self.assertFalse(path.exists()) - else: - self.assertTrue(path.is_file()) - self.assertFalse(any(p.name.startswith(".wave-reverse-") for p in out.iterdir())) - if not failure: - source_bytes = b"\n".join((ROOT / p).read_bytes() for p in ["reverse/wave/amd64.wave", "reverse/wave/cfg.wave"]) - self.assertEqual((out / helper.METADATA_NAME).read_text(), helper.fingerprint_metadata(source_bytes, b"new archive")) - import json - provenance = json.loads((out / "provenance.json").read_text()) - self.assertEqual(provenance["archive_sha256"], helper.digest(out / names[0])) - self.assertEqual(provenance["wave_revision"], helper.WAVE_REVISION) - - def test_success_publishes_matching_fingerprints_and_provenance(self): - self.publication() - - def test_failures_preserve_complete_last_good_set(self): - for failure in ["bootstrap", "compile", "archive"]: - with self.subTest(failure=failure): - self.publication(failure) - - def test_failures_never_publish_partial_first_build(self): - for failure in ["bootstrap", "compile", "archive"]: - with self.subTest(failure=failure): - self.publication(failure, existing=False) - - -class GuardTests(unittest.TestCase): - @classmethod - def setUpClass(cls): - cls.temporary = tempfile.TemporaryDirectory() - cls.guard = Path(cls.temporary.name) / "guard" - subprocess.run([shutil.which("rustc") or "rustc", str(ROOT / "reverse/build.rs"), - "--edition=2021", "-o", str(cls.guard)], check=True, capture_output=True) - - @classmethod - def tearDownClass(cls): - cls.temporary.cleanup() - - def test_fnv_known_vectors(self): - self.assertEqual(helper.fnv64(b""), "cbf29ce484222325") - self.assertEqual(helper.fnv64(b"hello"), "a430d84680aabd0b") - - def run_guard(self, corruption=None, enabled=True): - with tempfile.TemporaryDirectory() as directory: - root = Path(directory) - kernels = root / "wave" - kernels.mkdir() - (kernels / "amd64.wave").write_bytes(b"decode\n") - (kernels / "cfg.wave").write_bytes(b"cfg\n") - archive = root / "libwhale_wave_reverse.a" - archive.write_bytes(b"archive") - metadata = root / helper.METADATA_NAME - metadata.write_text(helper.fingerprint_metadata(b"decode\n\ncfg\n", b"archive")) - if corruption == "source": - (kernels / "cfg.wave").write_bytes(b"changed") - elif corruption == "archive": - archive.write_bytes(b"partial archive") - elif corruption == "abi": - metadata.write_text(metadata.read_text().replace("abi_version=1", "abi_version=2")) - elif corruption == "missing": - metadata.unlink() - elif corruption == "duplicate": - metadata.write_text(metadata.read_text() + "schema=1\n") - elif corruption == "oversized": - metadata.write_text("x" * 4097) - env = os.environ.copy() - env.update(CARGO_MANIFEST_DIR=str(root), HOST="x86_64-unknown-linux-gnu", - TARGET="x86_64-unknown-linux-gnu", WHALE_WAVE_REVERSE_DIR=str(root)) - env.pop("CARGO_FEATURE_WAVE", None) - if enabled: - env["CARGO_FEATURE_WAVE"] = "1" - return subprocess.run([str(self.guard)], env=env, capture_output=True, text=True) - - def test_matching_guard_passes_and_tracks_every_input(self): - result = self.run_guard() - self.assertEqual(result.returncode, 0, result.stderr) - for path in ["amd64.wave", "cfg.wave", "reverse-core.meta", "libwhale_wave_reverse.a"]: - self.assertIn("cargo:rerun-if-changed=", result.stdout) - self.assertIn(path, result.stdout) - self.assertIn("cargo:rustc-cfg=whale_wave_reverse", result.stdout) - - def test_stale_corrupt_and_wrong_abi_archives_are_rejected_before_link(self): - for corruption, reason in [("source", "stale"), ("archive", "corrupt"), - ("abi", "ABI revision"), ("missing", "missing"), - ("duplicate", "duplicate"), ("oversized", "oversized")]: - with self.subTest(corruption=corruption): - result = self.run_guard(corruption) - self.assertNotEqual(result.returncode, 0) - self.assertIn(reason, result.stderr) - self.assertNotIn("cargo:rustc-link-lib", result.stdout) - - @unittest.skipUnless(sys.platform == "linux" and os.uname().machine == "x86_64", "native bootstrap host") - def test_cargo_rechecks_warm_source_and_archive(self): - with tempfile.TemporaryDirectory() as directory: - project = Path(directory) - (project / "src").mkdir() - (project / "src/lib.rs").write_text("pub fn marker() {}\n") - (project / "Cargo.toml").write_text('[package]\nname="guard-probe"\nversion="0.0.0"\nedition="2021"\n[features]\nwave=[]\n') - shutil.copyfile(ROOT / "reverse/build.rs", project / "build.rs") - (project / "wave").mkdir() - for name in ["amd64.wave", "cfg.wave"]: - shutil.copyfile(ROOT / "reverse/wave" / name, project / "wave" / name) - out = project / "archive" - out.mkdir() - archive = out / "libwhale_wave_reverse.a" - archive.write_bytes(b"archive") - source = b"\n".join((project / "wave" / name).read_bytes() for name in ["amd64.wave", "cfg.wave"]) - (out / helper.METADATA_NAME).write_text(helper.fingerprint_metadata(source, b"archive")) - environment = os.environ.copy() - environment.update(WHALE_WAVE_REVERSE_DIR=str(out), CARGO_TARGET_DIR=str(project / "target")) - command = ["cargo", "check", "--offline", "--features", "wave", "--manifest-path", str(project / "Cargo.toml")] - - def check(success, reason=None): - result = subprocess.run(command, env=environment, capture_output=True, text=True) - self.assertEqual(result.returncode == 0, success, result.stderr) - if reason: - self.assertIn(reason, result.stderr) - - check(True) - cfg = project / "wave/cfg.wave" - original = cfg.read_bytes() - cfg.write_bytes(original + b"\n") - check(False, "stale Wave reverse archive") - cfg.write_bytes(original) - check(True) - archive.write_bytes(b"damaged archive") - check(False, "corrupt or mismatched") - archive.write_bytes(b"archive") - check(True) - - def test_feature_disabled_ignores_optional_archive(self): - result = self.run_guard("missing", enabled=False) - self.assertEqual(result.returncode, 0, result.stderr) - self.assertNotIn("cargo:rustc-link-lib", result.stdout) - - -if __name__ == "__main__": - unittest.main() diff --git a/tools/test_check_module_layers.py b/tools/test_check_module_layers.py new file mode 100644 index 0000000..2784fcb --- /dev/null +++ b/tools/test_check_module_layers.py @@ -0,0 +1,54 @@ +import copy +from pathlib import Path +import shutil +import tempfile +import tomllib +import unittest +from unittest.mock import patch + +import check_module_layers as layers + + +class LayerTests(unittest.TestCase): + def test_current_graph_has_no_concrete_isa_below_core(self): + graph = layers.audit()["production_dependencies"] + self.assertNotIn("amd64", graph["ir"]) + self.assertIn("object", graph["toolchain"]) + + def test_optional_and_target_conditional_dependencies_are_not_hidden(self): + manifest = { + "dependencies": {"a": {"path": "a", "optional": True}}, + "build-dependencies": {"b": {"path": "b"}}, + "dev-dependencies": {"c": {"path": "c"}}, + "target": {"cfg(windows)": {"dependencies": {"d": {"path": "d"}}}}, + } + self.assertEqual(list(layers.production_dependencies(manifest)), + [{"path": "a", "optional": True}, {"path": "b"}, {"path": "d"}]) + + def test_wrong_layer_fails_even_for_an_existing_dependency(self): + rules = copy.deepcopy(layers.CORE) + rules["backend-api"].remove("ir") + with patch.object(layers, "CORE", rules): + with self.assertRaisesRegex(ValueError, "backend-api.*forbidden.*ir"): + layers.audit() + + def test_concrete_isa_dependency_into_ir_is_rejected(self): + with tempfile.TemporaryDirectory() as temporary: + root = Path(temporary) + workspace = tomllib.loads((layers.ROOT / "Cargo.toml").read_text())["workspace"] + for member in [".", *workspace["members"]]: + path = layers.ROOT / member / "Cargo.toml" + relative = path.relative_to(layers.ROOT) + destination = root / relative + destination.parent.mkdir(parents=True, exist_ok=True) + shutil.copyfile(path, destination) + manifest = root / "ir/Cargo.toml" + with manifest.open("a") as stream: + stream.write('\n[target.\'cfg(windows)\'.dependencies]\n' + 'amd64 = { path = "../assembler/amd64", optional = true }\n') + with self.assertRaisesRegex(ValueError, "ir.*forbidden.*amd64"): + layers.audit(root) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/test_meson_build.py b/tools/test_meson_build.py new file mode 100644 index 0000000..0b082b3 --- /dev/null +++ b/tools/test_meson_build.py @@ -0,0 +1,219 @@ +# SPDX-License-Identifier: MPL-2.0 +"""Meson/Cargo bridge checks independent of installed Rust/Wave compilers.""" + +import argparse +import os +from pathlib import Path +import subprocess +import tempfile +import unittest +from unittest.mock import patch + +from meson_cargo import (BuildError, build, cargo_command, cargo_dependencies, + cargo_environment, make_escape, native_target, + smoke, source_dependencies, validate_features, validate_host) + + +class CommandTests(unittest.TestCase): + def test_product_features_do_not_choose_the_executable_host(self): + command = cargo_command("cargo", Path("source"), Path("private"), "aarch64-unknown-linux-gnu", + "dev", ["asm-amd64"], True, 2) + self.assertIn("--locked", command) + self.assertIn("--no-default-features", command) + self.assertIn("--offline", command) + self.assertEqual(command[command.index("--target") + 1], "aarch64-unknown-linux-gnu") + self.assertEqual(command[command.index("--features") + 1], "asm-amd64") + self.assertNotIn("--workspace", command) + + def test_no_isa_product_has_no_implicit_default_features(self): + command = cargo_command("cargo", Path("source"), Path("private"), "native-host", "dev", [], False, 1) + self.assertNotIn("--features", command) + self.assertIn("--no-default-features", command) + self.assertNotIn("--offline", command) + + def test_ambient_wave_and_cargo_target_cannot_change_selection(self): + with patch.dict(os.environ, {"WHALE_ASMOBJ_DIR": "old", "CARGO_BUILD_TARGET": "old"}): + environment = cargo_environment("private", None, "dev", "2", "2") + self.assertNotIn("WHALE_ASMOBJ_DIR", environment) + self.assertNotIn("CARGO_BUILD_TARGET", environment) + self.assertEqual(environment["CARGO_TARGET_DIR"], "private") + self.assertEqual(environment["CARGO_PROFILE_DEV_OPT_LEVEL"], "2") + self.assertEqual(environment["CARGO_PROFILE_DEV_DEBUG"], "2") + + def test_wave_is_explicit_and_unknown_features_fail(self): + self.assertEqual(validate_features(["asm-amd64", "asm-amd64"]), ["asm-amd64"]) + for features in [["unknown"], ["wave-reverse"]]: + with self.subTest(features=features), self.assertRaises(BuildError): + validate_features(features) + + def test_native_host_is_observed_only_when_requested_at_build(self): + result = subprocess.CompletedProcess([], 0, stdout="cargo 1.96\nhost: x86_64-unknown-linux-gnu\n") + with patch("meson_cargo.subprocess.run", return_value=result) as execute: + self.assertEqual(native_target("cargo", ".", {}), "x86_64-unknown-linux-gnu") + self.assertEqual(execute.call_args.args[0], ["cargo", "-vV"]) + with patch("meson_cargo.subprocess.run", return_value=subprocess.CompletedProcess([], 0, stdout="bad")): + with self.assertRaises(BuildError): + native_target("cargo", ".", {}) + + def test_rust_target_must_match_the_configured_meson_host(self): + cfg = 'target_arch="aarch64"\ntarget_os="linux"\ntarget_env="gnu"\n' + with patch("meson_cargo.subprocess.run", return_value=subprocess.CompletedProcess([], 0, stdout=cfg)): + validate_host("rustc", "aarch64-unknown-linux-gnu", "linux", "aarch64", ".", {}) + with self.assertRaisesRegex(BuildError, "disagrees with Meson host"): + validate_host("rustc", "aarch64-unknown-linux-gnu", "linux", "x86_64", ".", {}) + + def test_explicit_runner_arguments_remain_exact_without_a_shell(self): + with tempfile.TemporaryDirectory() as temporary: + binary = Path(temporary).resolve() / "whale" + binary.write_bytes(b"binary") + arguments = argparse.Namespace(binary=binary, feature=[], + runner_arg=["wrapper with space", "-L", "literal $sysroot"]) + + def answer(command, **kwargs): + self.assertEqual(command[:4], ["wrapper with space", "-L", "literal $sysroot", str(binary)]) + self.assertNotIn("shell", kwargs) + if command[-1] == "--version": + return subprocess.CompletedProcess(command, 0, b"whale 0.1.0\n", b"") + if "asm" in command: + return subprocess.CompletedProcess(command, 1, b"", b"Error: unregistered assembler; available: \n") + return subprocess.CompletedProcess(command, 0, b"i32 42\n", b"") + + with patch("meson_cargo.subprocess.run", side_effect=answer) as execute: + smoke(arguments) + self.assertEqual(execute.call_count, 3) + + +class DependencyTests(unittest.TestCase): + def test_depfile_roundtrip_handles_spaces_unicode_and_make_metacharacters(self): + dependencies = ["/source with space/α.rs", "/source/hash#dollar$.rs", r"C:\source folder\a.rs"] + with tempfile.TemporaryDirectory() as temporary: + path = Path(temporary).resolve() / "cargo.d" + path.write_text(make_escape("/build with space/whale") + ": " + + " ".join(map(make_escape, dependencies)) + "\n", encoding="utf-8") + self.assertEqual(cargo_dependencies(path), dependencies) + + def test_depfile_continuations_and_windows_drive_colons(self): + with tempfile.TemporaryDirectory() as temporary: + path = Path(temporary).resolve() / "cargo.d" + path.write_text("C:\\build\\whale.exe: C:\\src\\one.rs \\\n /src/two.rs\n\nother: ignored\n") + self.assertEqual(cargo_dependencies(path), [r"C:\src\one.rs", "/src/two.rs"]) + + def test_malformed_depfile_fails_instead_of_publishing_untracked_binary(self): + with tempfile.TemporaryDirectory() as temporary: + path = Path(temporary).resolve() / "cargo.d" + path.write_text("no dependency rule\n") + with self.assertRaises(BuildError): + cargo_dependencies(path) + + def test_source_dirs_and_manifests_track_additions_without_disabled_isas(self): + with tempfile.TemporaryDirectory() as temporary: + source = Path(temporary).resolve() + for name in ["src", "assembler/amd64/src", "assembler/aarch64/src"]: + (source / name).mkdir(parents=True) + (source / name / "lib.rs").write_text("// source") + (source / "Cargo.toml").write_text("manifest") + dependencies = source_dependencies(source, ["asm-aarch64"]) + self.assertIn(source / "assembler/aarch64/src", dependencies) + self.assertIn(source / "assembler/aarch64/src/lib.rs", dependencies) + self.assertNotIn(source / "assembler/amd64/src/lib.rs", dependencies) + self.assertIn(source / "Cargo.toml", dependencies) + + +class PublicationTests(unittest.TestCase): + def setUp(self): + self.temporary = tempfile.TemporaryDirectory() + self.addCleanup(self.temporary.cleanup) + self.root = Path(self.temporary.name).resolve() + self.source = self.root / "source tree" + self.source.mkdir() + self.target = self.root / "private target" + self.output = self.root / "whale" + self.output.write_bytes(b"previous") + self.depfile = self.root / "whale.d" + self.depfile.write_bytes(b"previous dependencies") + self.arguments = argparse.Namespace(source_root=self.source, target_dir=self.target, + output=self.output, depfile=self.depfile, asmobj_dir=None, feature=[], + profile="dev", opt_level="0", debug_info="2", host_target="x86_64-unknown-linux-gnu", + cargo="explicit cargo", rustc="explicit rustc", offline=True, jobs=2, + host_system="linux", host_cpu_family="x86_64") + + def fake_build(self, command, **kwargs): + if "--print" in command: + return subprocess.CompletedProcess(command, 0, stdout='target_arch="x86_64"\ntarget_os="linux"\n') + binary_dir = self.target / self.arguments.host_target / "debug" + binary_dir.mkdir(parents=True) + (binary_dir / "whale").write_bytes(b"new executable") + (binary_dir / "whale").chmod(0o755) + os.utime(binary_dir / "whale", (1, 1)) + (binary_dir / "whale.d").write_text(make_escape(binary_dir / "whale") + ": " + + make_escape(self.source / "src/lib.rs") + "\n") + return subprocess.CompletedProcess(command, 0) + + def test_failed_cargo_preserves_last_good_binary_and_dependencies(self): + with patch("meson_cargo.subprocess.run", side_effect=subprocess.CalledProcessError(1, ["cargo"])): + with self.assertRaises(subprocess.CalledProcessError): + build(self.arguments) + self.assertEqual(self.output.read_bytes(), b"previous") + self.assertEqual(self.depfile.read_bytes(), b"previous dependencies") + + def test_success_publishes_binary_and_actual_dependency_file(self): + with patch("meson_cargo.subprocess.run", side_effect=self.fake_build) as execute: + build(self.arguments) + self.assertEqual(self.output.read_bytes(), b"new executable") + built = self.target / self.arguments.host_target / "debug/whale" + self.assertEqual(self.output.stat().st_mode & 0o777, built.stat().st_mode & 0o777) + self.assertGreater(self.output.stat().st_mtime, 1) + self.assertIn(str(self.source / "src/lib.rs"), cargo_dependencies(self.depfile)) + self.assertEqual(execute.call_count, 2) # rustc cfg validation, then Cargo. + self.assertEqual(list(self.root.glob(".whale-*")), []) + + def test_missing_depfile_keeps_previous_binary(self): + def no_depfile(command, **kwargs): + result = self.fake_build(command, **kwargs) + if "--print" not in command: + (self.target / self.arguments.host_target / "debug/whale.d").unlink() + return result + with patch("meson_cargo.subprocess.run", side_effect=no_depfile): + with self.assertRaises(OSError): + build(self.arguments) + self.assertEqual(self.output.read_bytes(), b"previous") + + def test_failed_binary_replace_preserves_old_executable(self): + actual_replace = os.replace + + def replace(source, destination): + if destination == self.output: + raise OSError("injected publication failure") + return actual_replace(source, destination) + + with patch("meson_cargo.subprocess.run", side_effect=self.fake_build), \ + patch("meson_cargo.os.replace", side_effect=replace): + with self.assertRaises(OSError): + build(self.arguments) + self.assertEqual(self.output.read_bytes(), b"previous") + self.assertEqual(list(self.root.glob(".whale-*")), []) + + def test_root_cargo_target_dir_is_rejected_before_running_cargo(self): + self.arguments.target_dir = self.source / "target" + with patch("meson_cargo.subprocess.run") as execute: + with self.assertRaisesRegex(BuildError, "private Cargo"): + build(self.arguments) + execute.assert_not_called() + + def test_publication_replaces_output_symlink_without_touching_its_target(self): + source_file = self.source / "must-stay.txt" + source_file.write_bytes(b"source bytes") + self.output.unlink() + try: + self.output.symlink_to(source_file) + except (OSError, NotImplementedError) as error: + self.skipTest(str(error)) + with patch("meson_cargo.subprocess.run", side_effect=self.fake_build): + build(self.arguments) + self.assertFalse(self.output.is_symlink()) + self.assertEqual(self.output.read_bytes(), b"new executable") + self.assertEqual(source_file.read_bytes(), b"source bytes") + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/test_wave_bootstrap.py b/tools/test_wave_bootstrap.py new file mode 100644 index 0000000..80ee372 --- /dev/null +++ b/tools/test_wave_bootstrap.py @@ -0,0 +1,235 @@ +# SPDX-License-Identifier: MPL-2.0 +import io +import json +import os +from pathlib import Path +import subprocess +import tarfile +import tempfile +import unittest +from unittest.mock import patch + +import wave_bootstrap as bootstrap + + +class BootstrapTests(unittest.TestCase): + def setUp(self): + self.temporary = tempfile.TemporaryDirectory() + self.addCleanup(self.temporary.cleanup) + self.root = Path(self.temporary.name).resolve() + self.source = self.root / "Wave" + self.source.mkdir() + self.marker = self.source / "unrelated.wave" + self.marker.write_bytes(b"uncommitted changes stay here") + self.output = self.root / "cache" + self.calls = [] + self.rustc = "rustc 1.89.0 (test)" + self.version = "wavec 0.0.1-alpha-dev (test host)\n backend: LLVM 21.1.8" + self.failure = None + archive = io.BytesIO() + with tarfile.open(fileobj=archive, mode="w") as tree: + for name, data in {"Cargo.toml": b'[package]\nname="wavec"\nversion="0.0.1-alpha-dev"\n', + "Cargo.lock": b"pinned lockfile", "std/base.wave": b"pub const X: u32 = 1;"}.items(): + member = tarfile.TarInfo(name) + member.size = len(data) + tree.addfile(member, io.BytesIO(data)) + self.archive = archive.getvalue() + self.check = patch.object(bootstrap.subprocess, "check_output", side_effect=self.check_output).start() + self.run = patch.object(bootstrap, "run", side_effect=self.run_build).start() + self.addCleanup(patch.stopall) + + def check_output(self, command, **kwargs): + arguments = list(map(str, command)) + self.calls.append(arguments) + if arguments[0] == "git": + self.assertEqual(arguments[1:3], ["-C", str(self.source)]) + self.assertNotIn("checkout", arguments) + self.assertNotIn("reset", arguments) + if "archive" in arguments: + return self.archive + return "a" * 40 if arguments[-1].endswith(":std") else bootstrap.WAVE_REVISION + if arguments[0] == "rustup": + self.assertEqual(arguments[1:], ["which", "--toolchain", "1.89", "rustc"]) + if self.failure == "toolchain": + raise subprocess.CalledProcessError(1, arguments) + return "/installed/rustc" + if arguments[0] == "/installed/rustc": + return self.rustc + self.assertEqual(arguments[1:], ["--version"]) + if self.failure == "version" and "candidate" in arguments[0]: + return "wavec 99.0.0 (wrong)" + return self.version + + def run_build(self, command, **kwargs): + arguments = list(map(str, command)) + self.assertEqual(arguments[:5], ["cargo", "+1.89", "build", "--locked", "--jobs"]) + self.assertNotEqual(kwargs["cwd"], self.source) + self.assertEqual(kwargs["env"]["WAVE_STD_REVISION"], bootstrap.WAVE_REVISION) + self.assertEqual(kwargs["env"]["CARGO_INCREMENTAL"], "0") + self.assertEqual(kwargs["env"]["RUSTUP_AUTO_INSTALL"], "0") + self.assertIn("--bin", arguments) + if self.failure == "build": + raise subprocess.CalledProcessError(1, arguments) + compiler = self.output / "build/debug" / ("wavec.exe" if os.name == "nt" else "wavec") + compiler.parent.mkdir(parents=True, exist_ok=True) + compiler.write_bytes(b"pinned compiler") + compiler.chmod(0o755) + + def ensure(self, **kwargs): + result = bootstrap.ensure_bootstrap(self.source, self.output, rust_toolchain="1.89", **kwargs) + self.assertEqual(self.marker.read_bytes(), b"uncommitted changes stay here") + return result + + def test_build_publishes_compiler_std_and_provenance_as_one_generation(self): + result = self.ensure() + self.assertFalse(result.reused) + self.assertEqual(result.compiler.parent, result.std_root.parent) + self.assertEqual(result.compiler.parent, result.provenance.parent) + self.assertEqual(result.metadata["std_revision"], bootstrap.WAVE_REVISION) + self.assertEqual(result.metadata["std_tree"], "a" * 40) + self.assertEqual(result.metadata["compiler_sha256"], bootstrap.digest(result.compiler)) + self.assertEqual(result.metadata["std_sha256"], bootstrap._std_digest(result.std_root)) + self.assertEqual(result.metadata, json.loads(result.provenance.read_text())) + self.assertIn("--offline", self.run.call_args.args[0]) + self.assertEqual(self.run.call_args.kwargs["env"]["CARGO_NET_OFFLINE"], "true") + self.assertFalse(any(path.name.startswith(".wave-bootstrap-") for path in self.output.iterdir())) + + def test_second_build_validates_and_reuses_cache_without_cargo_or_archive(self): + first = self.ensure() + second = self.ensure() + self.assertTrue(second.reused) + self.assertEqual(first.compiler, second.compiler) + self.assertEqual(self.run.call_count, 1) + self.assertEqual(sum("archive" in call for call in self.calls), 1) + + def test_allow_network_is_explicit_and_never_installs_rust(self): + self.ensure(allow_network=True) + self.assertNotIn("--offline", self.run.call_args.args[0]) + self.assertFalse(any("install" in call for call in self.calls)) + + def test_stage_zero_does_not_inherit_final_host_or_whale_archives(self): + ambient = {"CARGO_BUILD_TARGET": "aarch64-unknown-linux-gnu", + "WHALE_WAVE_ELF_DIR": "/previous/elf", + "WHALE_WAVE_REVERSE_DIR": "/previous/reverse"} + with patch.dict(os.environ, ambient): + self.ensure() + environment = self.run.call_args.kwargs["env"] + for name in ambient: + self.assertNotIn(name, environment) + + def test_compiler_identity_probe_disables_ambient_terminal_colors(self): + def probe(command, **kwargs): + self.assertEqual(command, ["wavec", "--version"]) + self.assertEqual(kwargs["env"]["NO_COLOR"], "1") + self.assertEqual(kwargs["env"]["CLICOLOR"], "0") + self.assertEqual(kwargs["env"]["CLICOLOR_FORCE"], "0") + return self.version + + with patch.dict(os.environ, {"CLICOLOR": "1", "CLICOLOR_FORCE": "1"}): + os.environ.pop("NO_COLOR", None) + with patch.object(bootstrap.subprocess, "check_output", side_effect=probe): + self.assertEqual(bootstrap._compiler_version(Path("wavec")), self.version) + self.assertNotIn("NO_COLOR", os.environ) + self.assertEqual(os.environ["CLICOLOR_FORCE"], "1") + + def test_missing_or_wrong_rust_does_not_build_or_modify_source(self): + self.failure = "toolchain" + with self.assertRaises(subprocess.CalledProcessError): + self.ensure() + self.failure = None + self.rustc = "rustc 1.96.0 (wrong)" + with self.assertRaisesRegex(bootstrap.BootstrapError, "1.89.0"): + self.ensure() + self.run.assert_not_called() + self.assertFalse(self.output.exists()) + + def test_corrupt_compiler_and_std_are_rejected_before_cached_execution(self): + result = self.ensure() + original = result.compiler.read_bytes() + result.compiler.write_bytes(b"corrupt compiler") + self.check.reset_mock() + with self.assertRaisesRegex(bootstrap.BootstrapError, "compiler"): + bootstrap.load_bootstrap(self.output) + self.check.assert_not_called() + result.compiler.write_bytes(original) + (result.std_root / "base.wave").write_bytes(b"changed std") + with self.assertRaisesRegex(bootstrap.BootstrapError, "std"): + bootstrap.load_bootstrap(self.output) + self.check.assert_not_called() + + def test_revision_versions_hashes_and_pointer_paths_are_checked(self): + result = self.ensure() + original = result.provenance.read_text() + for field, value in (("std_revision", "b" * 40), ("wave_revision", "b" * 40), + ("std_tree", "not-a-tree"), ("wave_version", "99"), + ("schema", True), ("compiler_sha256", "bad")): + with self.subTest(field=field): + metadata = json.loads(original) + metadata[field] = value + result.provenance.write_text(json.dumps(metadata)) + with self.assertRaises(bootstrap.BootstrapError): + bootstrap.load_bootstrap(self.output) + result.provenance.write_text(original) + with self.assertRaisesRegex(bootstrap.BootstrapError, "std revision"): + bootstrap.load_bootstrap(self.output, std_tree="b" * 40) + (self.output / bootstrap.POINTER_NAME).write_text('{"schema":1,"generation":"../../Wave"}') + with self.assertRaisesRegex(bootstrap.BootstrapError, "pointer"): + bootstrap.load_bootstrap(self.output) + + def test_failed_rebuild_or_publication_preserves_last_good_generation(self): + first = self.ensure() + pointer = (self.output / bootstrap.POINTER_NAME).read_bytes() + files = {path: path.read_bytes() for path in (first.compiler, first.provenance, first.std_root / "base.wave")} + # A different Rust build identity requires a new generation while the + # pinned Rust release itself remains valid. + self.rustc = "rustc 1.89.0 (different build)" + for failure in ("build", "version", "publication"): + self.failure = failure + replace = os.replace + + def replacement(source, destination): + if failure == "publication" and Path(destination).name == bootstrap.POINTER_NAME: + raise OSError("interrupted publication") + return replace(source, destination) + + with self.subTest(failure=failure), patch.object(bootstrap.os, "replace", side_effect=replacement): + with self.assertRaises((bootstrap.BootstrapError, OSError, subprocess.CalledProcessError)): + self.ensure() + self.assertEqual((self.output / bootstrap.POINTER_NAME).read_bytes(), pointer) + self.assertEqual(list((self.output / "generations").iterdir()), [first.compiler.parent]) + for path, payload in files.items(): + self.assertEqual(path.read_bytes(), payload) + self.assertFalse(any(path.name.startswith(".wave-bootstrap-") for path in self.output.iterdir())) + + def test_failed_first_build_never_publishes_pointer_or_generation(self): + self.failure = "version" + with self.assertRaises(bootstrap.BootstrapError): + self.ensure() + self.assertFalse((self.output / bootstrap.POINTER_NAME).exists()) + self.assertFalse((self.output / "generations").exists()) + + def test_output_inside_read_only_checkout_is_rejected_before_any_commands(self): + with self.assertRaisesRegex(bootstrap.BootstrapError, "outside"): + bootstrap.ensure_bootstrap(self.source, self.source / "cache") + self.check.assert_not_called() + self.run.assert_not_called() + self.assertEqual(list(self.source.iterdir()), [self.marker]) + + def test_symlinked_std_or_build_directory_is_rejected(self): + result = self.ensure() + alias = result.std_root / "alias.wave" + try: + alias.symlink_to(self.marker) + except (OSError, NotImplementedError): + self.skipTest("symlinks unavailable") + with self.assertRaisesRegex(bootstrap.BootstrapError, "special file"): + bootstrap.load_bootstrap(self.output) + shutil = __import__("shutil") + shutil.rmtree(self.output / "build") + (self.output / "build").symlink_to(self.source, target_is_directory=True) + with self.assertRaisesRegex(bootstrap.BootstrapError, "symlinks"): + self.ensure() + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/wave_bootstrap.py b/tools/wave_bootstrap.py new file mode 100644 index 0000000..6ec7c1c --- /dev/null +++ b/tools/wave_bootstrap.py @@ -0,0 +1,276 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: MPL-2.0 +"""Build and reuse the pinned Wave compiler and std without editing its checkout. + +The default is offline. The cache publishes one immutable compiler/std/provenance +directory, then atomically replaces a small pointer file. No module registry or +SDK is involved; ordinary internal Wave build rules consume the returned paths. +""" + +import argparse +from dataclasses import dataclass +import hashlib +import io +import json +import os +from pathlib import Path +import platform +import re +import shutil +import stat +import subprocess +import tarfile +import tempfile +import uuid + + +WAVE_REVISION = "e0952ed65d07e14c6ed0aa64f3c9a5532dd7533b" +WAVE_VERSION = "0.0.1-alpha-dev" +RUST_VERSION = "1.89.0" +DEFAULT_RUST_TOOLCHAIN = "1.89.0" +CACHE_SCHEMA = 1 +POINTER_NAME = "bootstrap.json" +PROVENANCE_NAME = "provenance.json" + + +class BootstrapError(ValueError): + pass + + +@dataclass(frozen=True) +class Bootstrap: + compiler: Path + std_root: Path + provenance: Path + metadata: dict + reused: bool + + def paths(self): + return {"compiler": str(self.compiler), "std_root": str(self.std_root), + "provenance": str(self.provenance), "wave_revision": WAVE_REVISION, + "reused": self.reused} + + +def run(arguments, **kwargs): + subprocess.run(list(map(str, arguments)), check=True, **kwargs) + + +def digest(path): + result = hashlib.sha256() + with Path(path).open("rb") as source: + for chunk in iter(lambda: source.read(1024 * 1024), b""): + result.update(chunk) + return result.hexdigest() + + +def _std_digest(root): + """Hash sorted relative names and payloads; never follow cache symlinks.""" + root = Path(root) + if root.is_symlink() or not root.is_dir(): + raise BootstrapError("cached Wave std must be a regular directory") + result = hashlib.sha256() + count = total = 0 + for directory, directories, files in os.walk(root, followlinks=False): + directories.sort() + files.sort() + for name in directories: + if (Path(directory) / name).is_symlink(): + raise BootstrapError("cached Wave std contains a symlink") + for name in files: + path = Path(directory) / name + metadata = path.lstat() + if not stat.S_ISREG(metadata.st_mode): + raise BootstrapError("cached Wave std contains a special file") + count += 1 + total += metadata.st_size + if count > 8192 or total > 64 * 1024 * 1024: + raise BootstrapError("cached Wave std exceeds the bootstrap validation limit") + relative = path.relative_to(root).as_posix().encode("utf-8") + result.update(len(relative).to_bytes(4, "little")) + result.update(relative) + result.update(metadata.st_size.to_bytes(8, "little")) + result.update(bytes.fromhex(digest(path))) + if count == 0: + raise BootstrapError("cached Wave std is empty") + return result.hexdigest() + + +def _read_json(path, maximum): + if path.is_symlink() or not path.is_file() or path.stat().st_size > maximum: + raise BootstrapError("invalid or oversized bootstrap metadata") + try: + with path.open("rb") as source: + data = source.read(maximum + 1) + if len(data) > maximum: + raise BootstrapError("oversized bootstrap metadata") + return json.loads(data) + except (OSError, ValueError, UnicodeError, RecursionError) as error: + raise BootstrapError("invalid bootstrap metadata") from error + + +def _compiler_version(compiler): + environment = os.environ.copy() + environment.update(NO_COLOR="1", CLICOLOR="0", CLICOLOR_FORCE="0") + version = subprocess.check_output([str(compiler), "--version"], text=True, env=environment).strip() + if not version.startswith("wavec " + WAVE_VERSION + " ("): + raise BootstrapError(f"expected pinned Wave compiler version {WAVE_VERSION}") + return version + + +def _host(): + return platform.system().lower() + "-" + platform.machine().lower() + + +def load_bootstrap(out_dir, *, rustc=None, std_tree=None): + """Validate a published cache before returning executable/compiler paths.""" + output = Path(out_dir).resolve() + pointer = _read_json(output / POINTER_NAME, 4096) + if (not isinstance(pointer, dict) or set(pointer) != {"schema", "generation"} + or type(pointer["schema"]) is not int or pointer["schema"] != CACHE_SCHEMA + or not isinstance(pointer["generation"], str) + or not re.fullmatch(r"[a-f0-9]{32}", pointer["generation"])): + raise BootstrapError("invalid bootstrap cache pointer") + generation = output / "generations" / pointer["generation"] + if (output / "generations").is_symlink() or generation.is_symlink(): + raise BootstrapError("bootstrap generation must not be a symlink") + provenance = generation / PROVENANCE_NAME + metadata = _read_json(provenance, 16384) + required = {"schema", "wave_revision", "wave_version", "std_revision", "std_tree", + "std_sha256", "rustc", "rust_toolchain", "host", "compiler_version", + "compiler_sha256", "source_archive_sha256"} + if not isinstance(metadata, dict) or set(metadata) != required: + raise BootstrapError("invalid bootstrap provenance schema") + if (type(metadata["schema"]) is not int or metadata["schema"] != CACHE_SCHEMA + or metadata["wave_revision"] != WAVE_REVISION + or metadata["std_revision"] != WAVE_REVISION + or metadata["wave_version"] != WAVE_VERSION or metadata["host"] != _host() + or not isinstance(metadata["rustc"], str) + or not metadata["rustc"].startswith("rustc " + RUST_VERSION + " ") + or (rustc is not None and metadata["rustc"] != rustc) + or (std_tree is not None and metadata["std_tree"] != std_tree)): + raise BootstrapError("stale Wave compiler, Rust compiler or std revision in cache") + for field in ("std_sha256", "compiler_sha256", "source_archive_sha256"): + if not isinstance(metadata[field], str) or not re.fullmatch(r"[a-f0-9]{64}", metadata[field]): + raise BootstrapError("invalid bootstrap provenance digest") + if (not isinstance(metadata["std_tree"], str) + or not re.fullmatch(r"[a-f0-9]{40}", metadata["std_tree"]) + or not isinstance(metadata["rust_toolchain"], str) + or not metadata["rust_toolchain"]): + raise BootstrapError("invalid bootstrap compiler/std identity") + compiler = generation / ("wavec.exe" if os.name == "nt" else "wavec") + if compiler.is_symlink() or not compiler.is_file() or digest(compiler) != metadata["compiler_sha256"]: + raise BootstrapError("corrupt cached Wave compiler") + std_root = generation / "std" + if _std_digest(std_root) != metadata["std_sha256"]: + raise BootstrapError("corrupt cached Wave std") + # Hash and std checks precede execution of any cached compiler. + if _compiler_version(compiler) != metadata["compiler_version"]: + raise BootstrapError("cached Wave compiler version changed") + return Bootstrap(compiler, std_root, provenance, metadata, True) + + +def ensure_bootstrap(wave_source, out_dir, *, rust_toolchain=DEFAULT_RUST_TOOLCHAIN, + allow_network=False): + """Reuse a valid cache or build from git archive of the immutable pin.""" + repository = Path(wave_source).resolve() + output = Path(out_dir).resolve() + if output == repository or output.is_relative_to(repository): + raise BootstrapError("bootstrap output must be outside the read-only Wave checkout") + revision = subprocess.check_output( + ["git", "-C", str(repository), "rev-parse", WAVE_REVISION + "^{commit}"], text=True).strip() + if revision != WAVE_REVISION: + raise BootstrapError("Wave repository does not contain the pinned immutable commit") + std_tree = subprocess.check_output( + ["git", "-C", str(repository), "rev-parse", WAVE_REVISION + ":std"], text=True).strip() + if not re.fullmatch(r"[a-f0-9]{40}", std_tree): + raise BootstrapError("invalid pinned Wave std tree") + # `rustup which` never installs a missing toolchain. Do not let an implicit + # rustup download precede Cargo's explicit offline policy. + rustc_path = subprocess.check_output( + ["rustup", "which", "--toolchain", rust_toolchain, "rustc"], text=True).strip() + rustc = subprocess.check_output([rustc_path, "--version"], text=True).strip() + if not rustc.startswith("rustc " + RUST_VERSION + " "): + raise BootstrapError("the pinned Wave compiler requires installed Rust 1.89.0") + output.mkdir(parents=True, exist_ok=True) + if any((output / name).is_symlink() for name in ("build", "generations")): + raise BootstrapError("bootstrap build/cache directories must not be symlinks") + if (output / POINTER_NAME).exists(): + try: + return load_bootstrap(output, rustc=rustc, std_tree=std_tree) + except (BootstrapError, OSError, subprocess.SubprocessError): + # An invalid cache is rebuilt from the pin; its current generation + # remains untouched until the replacement is completely validated. + pass + environment = os.environ.copy() + # Stage 0 runs on this build machine; final Whale host selections and + # optional Whale archives must not leak into the compiler bootstrap. + environment.pop("CARGO_BUILD_TARGET", None) + environment.pop("WHALE_WAVE_ELF_DIR", None) + environment.pop("WHALE_ASMOBJ_DIR", None) + environment.pop("WHALE_WAVE_REVERSE_DIR", None) + environment.update(WAVE_STD_REVISION=WAVE_REVISION, CARGO_INCREMENTAL="0", RUSTUP_AUTO_INSTALL="0") + if not allow_network: + environment["CARGO_NET_OFFLINE"] = "true" + archive = subprocess.check_output( + ["git", "-C", str(repository), "archive", "--format=tar", WAVE_REVISION]) + with tempfile.TemporaryDirectory(prefix=".wave-bootstrap-", dir=output) as temporary: + temporary = Path(temporary) + source = temporary / "source" + source.mkdir() + with tarfile.open(fileobj=io.BytesIO(archive)) as tree: + tree.extractall(source, filter="data") + command = ["cargo", "+" + rust_toolchain, "build", "--locked", "--jobs", "2", + "--manifest-path", source / "Cargo.toml", "--target-dir", output / "build", "--bin", "wavec"] + if not allow_network: + command.append("--offline") + run(command, cwd=source, env=environment) + built = output / "build/debug" / ("wavec.exe" if os.name == "nt" else "wavec") + candidate = temporary / "candidate" + candidate.mkdir() + compiler = candidate / built.name + shutil.copy2(built, compiler) + shutil.copytree(source / "std", candidate / "std") + compiler_version = _compiler_version(compiler) + metadata = { + "schema": CACHE_SCHEMA, "wave_revision": WAVE_REVISION, + "wave_version": WAVE_VERSION, "std_revision": WAVE_REVISION, + "std_tree": std_tree, "std_sha256": _std_digest(candidate / "std"), + "rustc": rustc, "rust_toolchain": rust_toolchain, "host": _host(), + "compiler_version": compiler_version, "compiler_sha256": digest(compiler), + "source_archive_sha256": hashlib.sha256(archive).hexdigest(), + } + (candidate / PROVENANCE_NAME).write_text(json.dumps(metadata, indent=2) + "\n") + generation_id = uuid.uuid4().hex + generations = output / "generations" + generations.mkdir(exist_ok=True) + generation = generations / generation_id + pointer = temporary / POINTER_NAME + pointer.write_text(json.dumps({"schema": CACHE_SCHEMA, "generation": generation_id}) + "\n") + os.replace(candidate, generation) + try: + os.replace(pointer, output / POINTER_NAME) + except OSError: + shutil.rmtree(generation) + raise + return Bootstrap(generation / built.name, generation / "std", + generation / PROVENANCE_NAME, metadata, False) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--wave-source", required=True, type=Path) + parser.add_argument("--out-dir", required=True, type=Path) + parser.add_argument("--rust-toolchain", default=DEFAULT_RUST_TOOLCHAIN) + parser.add_argument("--allow-network", action="store_true", + help="explicitly permit Cargo dependency downloads; Rust must already be installed") + args = parser.parse_args() + try: + result = ensure_bootstrap(args.wave_source, args.out_dir, + rust_toolchain=args.rust_toolchain, allow_network=args.allow_network) + except (BootstrapError, OSError, subprocess.SubprocessError, tarfile.TarError) as error: + parser.exit(1, f"Wave bootstrap failed: {error}\n") + print(json.dumps(result.paths(), sort_keys=True)) + + +if __name__ == "__main__": + main()