#!/usr/bin/env bash # # CW(Xe): Script was generated by Claude after I tried to do this manually and # gave up. # # Build binaryen tools (wasm2js, wasm-opt) as WASI preview 1 WebAssembly # modules. See the TOOLS array below to add or remove targets. # # Output: ./_.wasm # (default wasm2js_130.wasm, wasm-opt_130.wasm) # # Dependencies are fetched automatically if missing: wasi-sdk is downloaded # from its GitHub release and binaryen is git-cloned at the requested tag. # Pin versions with the WASI_SDK_VERSION and BINARYEN_VERSION env vars. # # How it works / notable decisions: # # * Toolchain: we use the wasi-sdk CMake toolchain file `wasi-sdk-p1.cmake`, # which targets `wasm32-wasip1` and points CMake at the bundled clang/lld. # # * Static binary: WASI has no dynamic linker, so libbinaryen is built as a # static archive (-DBUILD_SHARED_LIBS=OFF) and statically linked into the # final module. This is the only thing that links on WASI. # # * C++ exceptions: binaryen's parser and tools use `throw`, so we cannot # build with -fno-exceptions. wasi-sdk ships two libc++ flavors: the default # `noeh` (no exceptions) and an `eh` variant. Passing `-fwasm-exceptions` # makes the clang driver select the `eh` include/lib dirs. We also link # `-lunwind` to satisfy the `_Unwind_*` / exception-tag symbols. # # * EH encoding: by default LLVM emits the *legacy* wasm exception-handling # opcodes (`try`/`catch`), which modern runtimes (e.g. wasmtime >= ~45) no # longer accept. `-mllvm -wasm-use-legacy-eh=false` makes it emit the # standardized exnref-based EH (`try_table`) instead, so the module runs on # current runtimes with the exceptions proposal enabled. # # * Threads: binaryen calls find_package(Threads) and links pthread (wasi-libc # provides stubs). At runtime ThreadPool::getNumCores() returns 1 on wasip1, # so no threads are ever spawned and it runs single-threaded. # # * Reproducibility: the goal is a byte-for-byte identical module on any # machine. Ninja invokes clang with absolute source paths, so __FILE__ # (used all over binaryen via WASM_UNREACHABLE) would otherwise bake the # build machine's checkout path into the module's data segments. We rewrite # that prefix to a stable token with -ffile-prefix-map so the output does # not depend on where the tree lives. Everything else feeding the module is # already pinned (wasi-sdk version, binaryen tag, compile/link flags), and # the wasm format carries no build timestamp, so the raw clang/lld output is # deterministic. We deliberately do NOT post-process with wasm-opt: its # availability and version vary per machine, which would defeat the # guarantee. Note this takes an explicit flag: clang's wasm driver runs # `wasm-opt -O3` on its own whenever a wasm-opt is on PATH and optimization # is on, so we pass --no-wasm-opt at link time to suppress it (see the # REPRO_LINK_FLAGS note below). # # * Clean build: cmake/ninja are incremental, so re-running over an existing # build tree only recompiles what changed and leaves stale object files # behind. If those objects were produced by an older revision of this script # (different flags), they leak into the final module and the output is no # longer a function of the current inputs alone. We therefore wipe the build # directory before configuring so every run is a full, flag-consistent build # from scratch. # # * Stripping: the linker emits ~2.5 MB of DWARF (.debug_*), a multi-megabyte # `name` section, and a `producers` section that records the exact clang # revision. The producers string in particular would tie the bytes to one # wasi-sdk build, and the debug/name sections only bloat a module we run # headless. We strip all of them with the wasi-sdk's OWN `llvm-strip` # (--strip-all), which is pinned by WASI_SDK_VERSION just like the compiler, # so the strip step is as deterministic as the rest of the toolchain. This # is NOT wasm-opt: llvm-strip ships in the sdk we already pin, so it adds no # new floating dependency. `target_features` is intentionally preserved -- # it advertises the proposals (exceptions, etc.) the module needs and # --strip-all keeps it. # # * ASLR: the wasi-sdk clang that compiles binaryen has address-sensitive # ordering in its WebAssembly exception-handling codegen -- pointer values # leak into the iteration order of a few passes, which shuffles a handful of # try_table basic blocks and their branch labels. With address-space layout # randomization on, the same source compiles to ~29 differing bytes from one # run to the next. We pin pointer layout by re-exec'ing the whole build under # `setarch -R` (ADDR_NO_RANDOMIZE), which is inherited by cmake/ninja/clang. # This is Linux-only; see the re-exec guard below. # # CAVEAT -- same architecture only. setarch fixes ASLR within one host, but # the underlying ordering is keyed on raw pointer VALUES (clang's # WebAssemblyCFGStackify iterates DenseMap in # pointer-hash order). The x86_64 and arm64 wasi-sdk clang binaries hand out # different pointers, so the two arches still produce ~29 differing bytes (a # few reordered try_table blocks) even though every section is otherwise # identical. This is an upstream LLVM determinism bug, not something we can # pin from here; fixing it needs LLVM to sort those EH pads by block number. # The committed modules are the x86_64 build; CI records the expected # checksums for both architectures (shasums.x86_64 / shasums.arm64) and # accepts a match against either, so each runner verifies its own arch. # # To run the resulting module, the host runtime must enable the exceptions # proposal and grant filesystem access, e.g.: # # wasmtime run -W exceptions=y --dir . ./wasm2js_130.wasm input.wasm -o out.js # set -euo pipefail # Pin any timestamp a tool in the chain might embed. Nothing in the current # toolchain consumes this (the wasm format has no build-time field and we emit # no debug info), but exporting it keeps the build deterministic if a future # wasi-sdk or binaryen starts honoring it. Fixed constant, not "now". export SOURCE_DATE_EPOCH="${SOURCE_DATE_EPOCH:-1700000000}" # Resolve the directory this script lives in so it works from anywhere. SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" cd "$SCRIPT_DIR" # --- Versions (override via the environment) ------------------------------- # wasi-sdk: full release version, e.g. 33.0. The GitHub release tag uses only # the major component (wasi-sdk-33) while the tarball uses the full version. WASI_SDK_VERSION="${WASI_SDK_VERSION:-34.0}" # binaryen: the numeric release, used both for the git tag (version_130) and # the output filename (wasm2js_130.wasm). BINARYEN_VERSION="${BINARYEN_VERSION:-130}" # Map the host's uname onto wasi-sdk's - asset naming. case "$(uname -s)" in Darwin) WASI_SDK_OS="macos" ;; Linux) WASI_SDK_OS="linux" ;; *) echo "error: unsupported OS $(uname -s); set WASI_SDK to a prebuilt sdk" >&2 exit 1 ;; esac case "$(uname -m)" in x86_64 | amd64) WASI_SDK_ARCH="x86_64" ;; arm64 | aarch64) WASI_SDK_ARCH="arm64" ;; *) echo "error: unsupported arch $(uname -m); set WASI_SDK to a prebuilt sdk" >&2 exit 1 ;; esac WASI_SDK_MAJOR="${WASI_SDK_VERSION%%.*}" WASI_SDK_DIRNAME="wasi-sdk-${WASI_SDK_VERSION}-${WASI_SDK_ARCH}-${WASI_SDK_OS}" WASI_SDK_URL="https://github.com/WebAssembly/wasi-sdk/releases/download/wasi-sdk-${WASI_SDK_MAJOR}/${WASI_SDK_DIRNAME}.tar.gz" BINARYEN_TAG="version_${BINARYEN_VERSION}" BINARYEN_URL="https://github.com/WebAssembly/binaryen.git" # All build inputs live under ./var; outputs land in the script directory. VAR_DIR="$SCRIPT_DIR/var" WASI_SDK="${WASI_SDK:-$VAR_DIR/$WASI_SDK_DIRNAME}" BINARYEN_SRC="$VAR_DIR/binaryen" BUILD_DIR="$BINARYEN_SRC/build-wasi" TOOLCHAIN="$WASI_SDK/share/cmake/wasi-sdk-p1.cmake" # llvm-strip from the same pinned wasi-sdk; used to drop debug/name/producers. STRIP="$WASI_SDK/bin/llvm-strip" mkdir -p "$VAR_DIR" # --- Fetch wasi-sdk --------------------------------------------------------- if [[ ! -f "$TOOLCHAIN" ]]; then echo ">> Downloading wasi-sdk $WASI_SDK_VERSION" echo " $WASI_SDK_URL" tmp_tarball="$(mktemp "$VAR_DIR/.wasi-sdk.XXXXXX.tar.gz")" trap 'rm -f "$tmp_tarball"' EXIT curl -fL --retry 3 -o "$tmp_tarball" "$WASI_SDK_URL" # The tarball unpacks to $WASI_SDK_DIRNAME/ in the destination directory. tar -xzf "$tmp_tarball" -C "$VAR_DIR" rm -f "$tmp_tarball" trap - EXIT fi if [[ ! -f "$TOOLCHAIN" ]]; then echo "error: wasi-sdk toolchain not found at $TOOLCHAIN" >&2 echo " set WASI_SDK to the wasi-sdk install prefix" >&2 exit 1 fi # --- Fetch binaryen --------------------------------------------------------- if [[ ! -d "$BINARYEN_SRC/.git" ]]; then echo ">> Cloning binaryen at $BINARYEN_TAG" git clone --depth 1 --branch "$BINARYEN_TAG" --recurse-submodules \ "$BINARYEN_URL" "$BINARYEN_SRC" fi # Flags that enable standardized wasm exception handling against wasi-sdk's # `eh` libc++ variant. Needed at both compile and link time. EH_COMPILE_FLAGS="-fwasm-exceptions -mllvm -wasm-use-legacy-eh=false" EH_LINK_FLAGS="-fwasm-exceptions -lunwind" # Reproducibility: strip the absolute checkout path out of every __FILE__ so the # module is identical regardless of where binaryen was cloned. BUILD_DIR lives # under BINARYEN_SRC, so generated-source paths are normalized by the same map. REPRO_COMPILE_FLAGS="-ffile-prefix-map=$BINARYEN_SRC=." # Reproducibility: clang's wasm driver silently runs `wasm-opt -O3` on the # linked module whenever an optimization level is set (Release => -O3) AND a # wasm-opt happens to be on PATH. That makes the bytes depend on whichever # wasm-opt is installed -- and an old one (e.g. the binaryen 108 that ships in # some distros) cannot even parse the exnref exception handling we emit, so the # link dies with "[parse exception: Bad type form -1] / error parsing wasm". # Disable the auto-pass so the module is purely the linker's deterministic # output (this is what the wasm-opt note in the header is really about). REPRO_LINK_FLAGS="--no-wasm-opt" # Reproducibility: start from a pristine build tree. cmake/ninja only rebuild # changed objects, so a stale tree from an earlier (differently-flagged) run # would silently contaminate the output. Wiping it guarantees the module is a # function of the current inputs alone. echo ">> Wiping build directory for a clean build" rm -rf "$BUILD_DIR" echo ">> Configuring (wasm32-wasip1, static, exceptions=exnref)" cmake -S "$BINARYEN_SRC" -B "$BUILD_DIR" -G Ninja \ -DCMAKE_TOOLCHAIN_FILE="$TOOLCHAIN" \ -DWASI_SDK_PREFIX="$WASI_SDK" \ -DCMAKE_BUILD_TYPE=Release \ -DBUILD_TESTS=OFF \ -DBUILD_SHARED_LIBS=OFF \ -DENABLE_WERROR=OFF \ -DINSTALL_LIBS=OFF \ -DCMAKE_C_FLAGS="$EH_COMPILE_FLAGS $REPRO_COMPILE_FLAGS" \ -DCMAKE_CXX_FLAGS="$EH_COMPILE_FLAGS $REPRO_COMPILE_FLAGS" \ -DCMAKE_EXE_LINKER_FLAGS="$EH_LINK_FLAGS $REPRO_LINK_FLAGS" # Tools to build, as binaryen CMake target names. Each is emitted to # ./_.wasm. TOOLS=(wasm2js wasm-opt) echo ">> Building: ${TOOLS[*]}" cmake --build "$BUILD_DIR" --target "${TOOLS[@]}" # Install the stripped linker output. We intentionally skip any wasm-opt pass: # optimizing here would make the result depend on whichever wasm-opt happens to # be installed, which is exactly the non-determinism we are eliminating. The # only post-processing is llvm-strip from the pinned wasi-sdk (see header note); # combined with the pinned toolchain and the -ffile-prefix-map applied above, # the module is reproducible. BUILD_BIN="$BUILD_DIR/bin" for tool in "${TOOLS[@]}"; do out="./${tool}_${BINARYEN_VERSION}.wasm" echo ">> Installing $tool -> $out (stripped)" "$STRIP" --strip-all "$BUILD_BIN/$tool" -o "$out" ls -l "$out" | awk '{print " size:", $5, "bytes"}' done echo ">> Done. Outputs in $SCRIPT_DIR:" ls -1 ./*_"${BINARYEN_VERSION}".wasm