#!/usr/bin/env bash # wasmld: wasm-ld wrapper. Produces statically linked .wasm modules suitable # for execution by HardwareJS. The user binary has: # - exported _start # - imported memory (HardwareJS supplies the WebAssembly.Memory) # - imported "linux.syscall" (and friends) # # TWO ARMS (HWJS-3, docs/HWJS-3-USERLAND-DESIGN.md §7): # # ── LEGACY ARM (WASMLD_HWJS=0, the default until the D1 targets migrate) ── # # D1-FORK.b: after linking, the module is run through Binaryen's Asyncify # pass with the host syscall import declared as the suspend point: # # wasm-opt -O2 --asyncify --pass-arg=asyncify-imports@linux.syscall # # This makes EVERY linux.syscall callsite an unwind/rewind point, which is # what real fork() needs: the parent's call stack is unwound at the fork # syscall, snapshotted, copied to the child, and both are rewound (parent # returns the child pid, child returns 0). Whole-program scope (no # asyncify-only-list) guarantees an arbitrary syscall-site is coverable. # The instrumentation is INERT when the asyncify state is NONE (normal # syscalls just call through), so non-forking binaries are unaffected # beyond size/throughput. See linux-wasm/Documentation/wasm/fork-model.rst # and the proof in linux-wasm/tools/d1-fork-spike/. # # Escape hatch: WASMLD_ASYNCIFY=0 links without the pass (pre-D1-FORK # behaviour) for A/B comparison. # # D1-BASH.b3 (R-D1BASH-W2): WASMLD_FPCAST_EMU=1 (default 0, OPT-IN per-build) # prepends Binaryen's --fpcast-emu (Function Pointer Cast Emulation) to the # wasm-opt invocation. This routes indirect calls through generated # signature-adapter thunks so a K&R-untyped-function-pointer call (bash's # `typedef int (*Function)()` unwind_protect cleanups) no longer trips wasm's # strict call_indirect type check. It is GLOBAL (rewrites the indirect-call # table to one uber-signature) and carries thunk/table-rewrite cost, so it is # OFF by default and enabled ONLY for binaries that need it (bash) — NOT the # kernel and NOT cast-clean binaries. --fpcast-emu runs BEFORE -O2 --asyncify in # the same wasm-opt invocation (proven to compose: linux-wasm/tools/ # d1-bash-fpcast-spike, 9/9). See ARCHITECTURE.md §15.3 R-D1BASH-W2. # # ── CORO ARM (WASMLD_HWJS=1 — the brintium substrate; HWJS-3) ── # # Whole-program vantage (design §1; the shape the toolchain's own whole-program # corpus scan established): wasmcc emitted every TU as BITCODE; this # wrapper merges the full program closure into ONE LLVM module — # # 1. llvm-link the bitcode roots (program objects + crt1_musl_hwjs.bc + # hwjs_user_rt.bc), # 2. archive-pull the pool (bitcode archive members + the musl bitcode # pool) with `llvm-link -only-needed`, ITERATED TO A FIXPOINT — the # scan's F71 lesson verbatim: -only-needed is a single left-to-right # pass, so a member that defines a symbol needed only by a LATER pull # is dropped; each iteration pulls what the previous result newly # references (converges in 2-3 passes), # 3. ONE pinned-clang compile of the merged module with the # HwjsCoroutinize plugin (PipelineStartEP), under the FULL cc-wasm.sh # guard suite — chimera guard, SUMMARY presence, protocol_forced=1, # parked_flag_forced=1 + parked_abi=2, DRIVE-CONTRACT drive_abi=3 # (flat, the DEFAULT) or drive_abi=2 (nested, under HWJS_CORO_DRIVE_NESTED), # REFUSE enforcement (sole benign class: alwaysinline-suspender- # residual real_uses=0; the weak-empty-default census class is # RETIRED at membership zero — any refusal here is a FRESH # stop-and-report), UNPUBLISHED-SUSPENDER visibility=external == 0 # (structural at whole-program vantage; checked anyway), and the # classify-only leak check, # 4. final wasm-ld with the native-stage objects (wasm_thread.k7.o, # hwjs_user_thunks.o, compiler-rt builtins). # # The Binaryen stage is GONE on this arm: NO wasm-opt, NO --asyncify, NO # --fpcast-emu (native fpcast rides the plugin; the kernel EH-guard's # reasoning applies — a coro-bearing module must never reach Binaryen). # WASMLD_FPCAST_EMU=1 alongside WASMLD_HWJS=1 is refused loudly. # A caller's exported POSIXLY_CORRECT (gnulib's getopt check) must not disable <(...). set +o posix set -euo pipefail # THE LINK'S OUTPUT. A link writes notes, the coroutinize pass's log and # attestations, and its tools' warnings: over a megabyte for a hello world. A # link that succeeds writes none of it to stderr. It goes to a hidden file # beside the output, /..hwjs-link.log for -o /, which each # link replaces; hidden, so a glob over the build directory does not install # it. A link that fails also replays it to stderr, so its diagnostics are # unchanged. No file is written for a line with no -o (nor for a compiler # driver's line with none, which links a.out), nor when the output's directory # is not writable or the output is not a regular file. # WASMLD_HWJS_LOG unset as above # WASMLD_HWJS_VERBOSE=1 as above, and stream to stderr as the link goes # WASMLD_HWJS_LOG=stderr stream to stderr as the link goes, and no file # WASMLD_HWJS_LOG=quiet stderr only when the link fails, and no file # WASMLD_HWJS_LOG= as quiet, and append each link's output to # Unset or quiet, WASMLD_HWJS_VERBOSE_PASS=1 or WASMLD_HWJS_KEEP mean # WASMLD_HWJS_VERBOSE=1: whoever sets them is there to read the output. # When the command line names the output, the output is collected in that # directory from the start, so a successful link pays one process for it: the # rename into place. In the guest every fork costs tens of milliseconds. # The gates read their own logs, never this. BRINTLD_ERR_LOG="" BRINTLD_ERR_KEEP="" BRINTLD_ERR_FD="" BRINTLD_RM_WORK="" # The file the output goes to: empty for none, "-" while the output is not known. BRINTLD_LINK_LOG="" BRINTLD_EARLY_OUT="" # The -o the caller named, and the directory of this link's own that the image # is written and checked in until brintld_place_out renames it there. BRINTLD_OUT="" BRINTLD_OUT_STAGE="" BRINTLD_TEE_PID="" BRINTLD_PWD="$PWD" brintld_verbose() { [[ "${WASMLD_HWJS_VERBOSE:-0}" != 0 || "${WASMLD_HWJS_VERBOSE_PASS:-0}" != 0 || -n "${WASMLD_HWJS_KEEP:-}" ]] } # brintld_link_log_v : the output's log file in BRINTLD_LINK_LOG_V, or 1. brintld_link_log_v() { local o="$1" d BRINTLD_LINK_LOG_V="" [[ -n "$o" ]] || return 1 [[ "$o" == /* ]] || o="$BRINTLD_PWD/$o" [[ ! -e "$o" || -f "$o" ]] || return 1 d="${o%/*}" [[ -d "${d:-/}" && -w "${d:-/}" ]] || return 1 BRINTLD_LINK_LOG_V="$d/.${o##*/}.hwjs-link.log" } # brintld_keep_pass_log : copies a pass log where it outlives $WORK (beside # the output, as ..hwjs-pass.log, else in $TMPDIR) and prints the path. brintld_keep_pass_log() { local dest="" f i t if brintld_link_log_v "${BRINTLD_OUT:-${OUT:-$BRINTLD_EARLY_OUT}}"; then dest="${BRINTLD_LINK_LOG_V%.hwjs-link.log}.hwjs-pass.log" else # A new file, created exclusively without a fork, as brintld_err_open does. for i in 1 2 3 4 5 6 7 8; do f="${TMPDIR:-/tmp}/brintld-pass.$$.$RANDOM" if { set -C; exec {t}>"$f"; } 2>/dev/null; then set +C; exec {t}>&-; dest="$f"; break fi set +C done [[ -n "$dest" ]] || return 1 fi cp -- "$1" "$dest" 2>/dev/null && printf '%s\n' "$dest" } # Moves the collected output to its log file. brintld_link_log_place() { local o="${BRINTLD_OUT:-${OUT:-$BRINTLD_EARLY_OUT}}" dest="$BRINTLD_LINK_LOG" t [[ -n "$o" ]] || return 0 if [[ "$dest" == - ]]; then brintld_link_log_v "$o" || return 0 dest="$BRINTLD_LINK_LOG_V" if [[ "${BRINTLD_ERR_LOG%/*}" != "${dest%/*}" ]]; then t="$dest.$$.$RANDOM" { cp -- "$BRINTLD_ERR_LOG" "$t" && mv -f -- "$t" "$dest"; } 2>/dev/null || rm -f -- "$t" || true return 0 fi fi mv -f -- "$BRINTLD_ERR_LOG" "$dest" 2>/dev/null && BRINTLD_ERR_LOG="" || true } brintld_on_exit() { local rc=$? cmd="$BASH_COMMAND" p fd sig="" # A command that fails under set -e exits with no message; an explicit exit # (fatal, a propagated status, the llvm-nm guard's USR1) has printed its own. if [[ $rc -ne 0 && -z "${BRINTLD_USR1:-}" && ! "$cmd" =~ ^exit([[:space:]]|$) ]]; then cmd="${cmd//$'\n'/ }" (( ${#cmd} <= 300 )) || cmd="${cmd:0:300}..." p="" for fd in "${FUNCNAME[@]:1:${#FUNCNAME[@]}-2}"; do p="${p:+$p, called from }$fd"; done [[ -z "$p" ]] || p=" (in $p)" (( rc <= 128 || rc > 192 )) || sig=" (128 + signal $(( rc - 128 )))" # A subshell takes the SIGPIPE of a closed stderr, so the cleanup below runs. ( echo "wasmld: FATAL (HWJS-3 coro arm): the link stopped at a failed step$p, status $rc$sig: $cmd" >&2 ) || true fi if [[ -n "$BRINTLD_ERR_LOG" ]]; then if [[ -n "$BRINTLD_TEE_PID" ]]; then # tee ends when every copy of its pipe is closed, the ones this script # made of stderr included, and it has to end before its file is read. for p in /proc/$$/fd/*; do fd="${p##*/}" [[ "$fd" =~ ^[0-9]+$ ]] && (( fd > 2 )) && [[ "$p" -ef /proc/$$/fd/2 ]] \ && { exec {fd}>&-; } 2>/dev/null || true done fi exec 2>&"$BRINTLD_ERR_FD" [[ -z "$BRINTLD_TEE_PID" ]] || wait "$BRINTLD_TEE_PID" 2>/dev/null || true if [[ -n "$BRINTLD_ERR_KEEP" ]]; then cat "$BRINTLD_ERR_LOG" >>"$BRINTLD_ERR_KEEP" \ || echo "wasmld: could not append this link's output to WASMLD_HWJS_LOG=$BRINTLD_ERR_KEEP" >&2 fi [[ $rc -eq 0 || -n "$BRINTLD_TEE_PID" ]] || cat "$BRINTLD_ERR_LOG" >&2 || true [[ -z "$BRINTLD_LINK_LOG" ]] || brintld_link_log_place fi # One rm for both: in the guest every fork costs tens of milliseconds. [[ -z "$BRINTLD_RM_WORK$BRINTLD_ERR_LOG${BRINTLD_OUT_STAGE:-}" ]] \ || rm -rf $BRINTLD_RM_WORK $BRINTLD_ERR_LOG ${BRINTLD_OUT_STAGE:+"$BRINTLD_OUT_STAGE"} || true } BRINTLD_USR1="" trap brintld_on_exit EXIT # brintld_err_open [dir [name]]: collects stderr into a new file. Opened without # a fork: noclobber makes the open exclusive. With tee as the third argument, # stderr also goes on to where it went. brintld_err_open() { local d="${1:-${TMPDIR:-/tmp}}" n="${2:-brintld-stderr}" f i t for i in 1 2 3 4 5 6 7 8; do f="$d/$n.$$.$RANDOM" if { set -C; exec {t}>"$f"; } 2>/dev/null; then set +C BRINTLD_ERR_LOG="$f" if [[ "${3:-}" == tee ]]; then exec {t}>&- {BRINTLD_ERR_FD}>&2 exec 2> >(exec tee -- "$f" >&"$BRINTLD_ERR_FD") BRINTLD_TEE_PID=$! else exec {BRINTLD_ERR_FD}>&2 2>&"$t" {t}>&- fi return 0 fi set +C done return 1 } # The -o of a line with no response file, which the expansion below leaves as # it is. It only places the collecting file: a line with a response file is read # once it is expanded (BRINTLD_EARLY_RSP=1), and its output is copied beside -o # at exit. BRINTLD_EARLY_RSP=0 brintld_early_out() { local i=1 a o="" while (( i <= $# )); do a="${!i}" [[ "$a" != @?* ]] || { BRINTLD_EARLY_RSP=1; return 0; } if [[ -z "$o" && "$a" == -o ]]; then i=$((i + 1)); o="${!i:-}" elif [[ -z "$o" && "$a" == -o* ]]; then o="${a#-o}" fi i=$((i + 1)) done BRINTLD_EARLY_OUT="$o" } # A pipe the caller shares with other writers may be non-blocking (make and # bitbake hand one down, and O_NONBLOCK belongs to the open file description, # so any process holding it can set it). A write to it when it is full then # fails with EAGAIN instead of waiting, and under set -e a failed write ends # a link that succeeded. Opening the pipe again through /proc gives this link # a description of its own, which blocks. Nothing changes when stderr is not # a pipe or /proc is missing. if [[ -p /proc/self/fd/2 ]]; then exec {_brintld_fd}>&2 if exec 2>/dev/null {_brintld_nb}>>"/proc/self/fd/$_brintld_fd"; then exec 2>&"$_brintld_nb" {_brintld_nb}>&- else exec 2>&"$_brintld_fd" fi exec {_brintld_fd}>&- fi unset _brintld_fd _brintld_nb case "${WASMLD_HWJS_LOG:-}" in "") # The compiler driver says when its caller named no -o (libexec/link-direct.sh). [[ "${WASMLD_HWJS_DRIVER_NO_OUT:-0}" == 1 ]] || brintld_early_out "$@" BRINTLD_LINK_LOG="" [[ "$BRINTLD_EARLY_RSP" == 0 ]] || BRINTLD_LINK_LOG=- _brintld_mode="" brintld_verbose && _brintld_mode=tee if [[ -n "$BRINTLD_EARLY_OUT" ]]; then BRINTLD_LINK_LOG="" if brintld_link_log_v "$BRINTLD_EARLY_OUT"; then BRINTLD_LINK_LOG="$BRINTLD_LINK_LOG_V" _brintld_n="${BRINTLD_LINK_LOG##*/}" brintld_err_open "${BRINTLD_LINK_LOG%/*}" "$_brintld_n" $_brintld_mode \ || BRINTLD_LINK_LOG="" fi fi if [[ -z "$BRINTLD_ERR_LOG" ]]; then [[ "$BRINTLD_LINK_LOG" == - ]] || BRINTLD_LINK_LOG="" brintld_err_open "" "" $_brintld_mode || BRINTLD_LINK_LOG="" fi unset _brintld_mode _brintld_n ;; stderr) ;; quiet) brintld_verbose || brintld_err_open || true ;; *) BRINTLD_ERR_KEEP="$WASMLD_HWJS_LOG" brintld_err_open \ || { echo "wasmld: FATAL: cannot create a file in ${TMPDIR:-/tmp} to collect this link's output for WASMLD_HWJS_LOG=$WASMLD_HWJS_LOG." >&2; exit 1; } ;; esac # The compiler driver's notes, held for this link (libexec/link-direct.sh). if [[ -n "${WASMLD_HWJS_DRIVER_NOTES:-}" ]]; then printf '%s' "$WASMLD_HWJS_DRIVER_NOTES" >&2 fi unset WASMLD_HWJS_DRIVER_NOTES WASMLD_HWJS_DRIVER_NO_OUT # PATH PROBES # # dirname and basename in the shell. path_dirname_v and path_basename_v answer # in $PATH_DIRNAME and $PATH_BASENAME what "$(dirname -- "$1")" and # "$(basename -- "$1")" hold, the trailing newlines the substitution strips # included, and start no process. The same block is in bin/brintcc, # libexec/config.sh, libexec/brintcc-glibc and libexec/brintld. path_dirname_v() { local _pd="$1" _pd="${_pd%"${_pd##*[!/]}"}" if [[ -z "$_pd" ]]; then if [[ -n "$1" ]]; then PATH_DIRNAME=/; else PATH_DIRNAME=.; fi elif [[ "$_pd" != */* ]]; then PATH_DIRNAME=. else _pd="${_pd%/*}" _pd="${_pd%"${_pd##*[!/]}"}" PATH_DIRNAME="${_pd:-/}" fi PATH_DIRNAME="${PATH_DIRNAME%"${PATH_DIRNAME##*[!$'\n']}"}" } path_basename_v() { local _pb="$1" _pb="${_pb%"${_pb##*[!/]}"}" if [[ -n "$_pb" ]]; then PATH_BASENAME="${_pb##*/}" elif [[ -n "$1" ]]; then PATH_BASENAME=/ else PATH_BASENAME= fi PATH_BASENAME="${PATH_BASENAME%"${PATH_BASENAME##*[!$'\n']}"}" } # End of the path probes. # brintium's canonical link driver. Paths derive from this checkout ($HWJS_HOME) # plus a small env interface; a downstream distro exports these to point the # SAME driver at its own build tree (see docs/BUILDING.md). No machine-specific # absolute path is baked in. path_dirname_v "${BASH_SOURCE[0]}" HWJS_HOME="$(cd "$PATH_DIRNAME/.." && pwd)" # RESPONSE FILES. clang hands the linker ONE argument, @file, once the link # line passes half of its 128 KB limit (llvm/lib/Support/Unix/Program.inc, # commandLineFitsWithinSystemLimits), and -o, -shared, -r and every input are # then inside that file. Everything below reads the command line, so the line # is expanded here, once, before the first reader: the rest of this script sees # the arguments wasm-ld would have seen. A line with no @ argument is not # touched, and one that was expanded says so on stderr. # shellcheck source=libexec/response-file.sh source "$HWJS_HOME/libexec/response-file.sh" RSP_TOOL=wasmld rsp_expand_line "$@" if (( RSP_FILES > 0 )); then echo "wasmld: NOTE (response file): $# argument(s) on the command line, ${#RSP_EXPANDED[@]} after expanding $RSP_FILES response file(s)." >&2 set -- ${RSP_EXPANDED[@]+"${RSP_EXPANDED[@]}"} fi # A CROSS LINK SEARCHES NO BUILD-HOST DIRECTORY # host_lib_drop_v ...: the link line in HOST_LIB_ARGS. clang's # wasm link job, and libexec/link-direct.sh after it, emit -m wasm32 # [--strip-all], the caller's -L and -u in order, and then -L/lib when the line # has no --sysroot. In the guest that is the target's /lib; on a build host it # is the host's own, whose x86-64 archives a -lNAME would pick. So on a machine # that is not wasm32 that one argument is dropped: the last -L of that leading # run, when it is exactly -L/lib. A caller's own -L stays. host_lib_drop_v() { local _m="$1" _i=2 _last=-1 shift HOST_LIB_ARGS=( "$@" ) [[ "$_m" != wasm32* ]] || return 0 [[ "${1:-}" == -m && "${2:-}" == wasm32 ]] || return 0 [[ "${3:-}" != --strip-all ]] || _i=3 while (( _i < $# )); do case "${HOST_LIB_ARGS[$_i]}" in -L?*) _last=$_i; _i=$((_i + 1)) ;; -u) _i=$((_i + 2)) ;; -u?*) _i=$((_i + 1)) ;; *) break ;; esac done (( _last >= 0 )) || return 0 [[ "${HOST_LIB_ARGS[$_last]}" == -L/lib ]] || return 0 HOST_LIB_ARGS=( "${HOST_LIB_ARGS[@]:0:_last}" "${HOST_LIB_ARGS[@]:_last+1}" ) } # Whether this link runs in the guest: the toolchain's own machine, wasm32 there. HWJS_MACHINE="$(uname -m)" || { echo "wasmld: FATAL: uname -m failed: whether this link runs in the guest is unknown." >&2; exit 1; } host_lib_drop_v "$HWJS_MACHINE" "$@" set -- ${HOST_LIB_ARGS[@]+"${HOST_LIB_ARGS[@]}"} # Every read a link makes of a wasm file goes to libexec/brint-tool: pool # selection, the hwjs.abi reads, the import witness, the consult export, and # the reads of libc.so, needed libraries, -shared and dynamic-main links. An # installed toolchain ships it; a source checkout builds it with # helper/build.sh. Read from the tree on every exec, never from the environment. BRINT_TOOL="$HWJS_HOME/libexec/brint-tool" [[ -x "$BRINT_TOOL" ]] || { echo "wasmld: FATAL: no brint-tool at $BRINT_TOOL -- every link reads its inputs and its output through it. Build it with $HWJS_HOME/helper/build.sh" >&2 exit 1 } # real_path FILE: FILE with every symlink resolved, on stdout, or a failure # with the reason on stderr. real_path() { "$BRINT_TOOL" realpath "$1" } # export_names FILE: the names FILE exports, one a line. export_names() { "$BRINT_TOOL" exports "$1" } # An installed toolchain has no checkout to read a commit from (the wasm32 # guest's is bin/ and libexec/ alone). Its installer records the brintium commit # these scripts came from in libexec/hwjs-installed.stamp: one line, # commit=<40 hex>, the format of a plugin's .stamp. Read from the tree on # every exec, like the helper above. Where it exists it is what the plugins' # PLUGIN-PROVENANCE attestation is held to, in place of a checkout's HEAD. HWJS_INSTALLED_STAMP="$HWJS_HOME/libexec/hwjs-installed.stamp" # shellcheck source=libexec/find-llvm.sh source "$HWJS_HOME/libexec/find-llvm.sh" # shellcheck source=libexec/link-facts.sh source "$HWJS_HOME/libexec/link-facts.sh" # shellcheck source=libexec/builtins-forms.sh source "$HWJS_HOME/libexec/builtins-forms.sh" # shellcheck source=libexec/ld-script.sh source "$HWJS_HOME/libexec/ld-script.sh" # Base for build artifacts the LINK consumes (the libc bitcode pool, the # startfiles, the builtins): the sysroot tree, a directory of this checkout. # The default was the checkout ROOT, from when those artifacts were produced # by a separate repository that always exported this variable — so the default # was never exercised and pointed one level above them. bin/brintld resolves # and exports it for every real link. HWJS_TOOLS_DIR="${HWJS_TOOLS_DIR:-${BRINTIUM_SYSROOT:-$HWJS_HOME/sysroot}}" # ── ONE HOME FOR THE DERIVED PASS PLUGINS ──────────────────────────────────── # # THE DEFECT THIS REPLACES. The plugins are derived artifacts of THIS checkout, # and they used to have two homes with independent freshness: this checkout's # own cmake tree, and a build tree that a consuming super-repo installed them # into. Which one a given link used depended on whether its particular caller # remembered to export WASMLD_HWJS_*_PLUGIN. That is a per-consumer convention, # and it failed the way conventions fail: one consumer shim exported none of # them, another exported two of three (witnessed: a libc.so link that died # PLUGIN-PROVENANCE mismatch on HwjsEHPreLower ONLY), and the refusal message # named a remedy — "rebuild it" — that refreshed the home the link was not # using, so an operator could run the stated fix, see it report success, and # get the identical failure. Four separate efforts paid for that. # # THE RULE. This repository has exactly one command that produces plugins # (toolchain/build.sh) and exactly one directory it produces them into, so # there is exactly one home and nothing to choose between: # # $HWJS_HOME/pass/coroutinize/build # # NOT $HWJS_TOOLS_DIR/build, which is where the libc bitcode pool, the # startfiles and the builtins archive come from. That tree is produced by the # libc build; nothing in it produces plugins. Carrying it as a second candidate # would be the same two-ages defect in its most degenerate form — one of the # two ages being "never built", so a link would refuse naming a directory no # command in this repository fills. # # There is no fallback and no second candidate: a missing plugin refuses and # names this path and the command that fills it. Explicit WASMLD_HWJS_*_PLUGIN # still wins everywhere, which is the supported way to point one link at an # experimental plugin without moving the home. HWJS_PLUGIN_HOME="$HWJS_HOME/pass/coroutinize/build" # The remedy that refreshes THAT home, quoted verbatim in every refusal below # so a message can never name a fix that refreshes something else. HWJS_PLUGIN_REMEDY="$HWJS_HOME/toolchain/build.sh (builds the plugins into that directory and refuses if any of them is missing afterwards)" # An installed tree has no toolchain/build.sh to name. [[ -e "$HWJS_INSTALLED_STAMP" ]] && HWJS_PLUGIN_REMEDY="reinstall the toolchain, so that its drivers, its plugins and $HWJS_INSTALLED_STAMP come from one build" # Every LLVM tool resolves from the pinned from-source build (override the bin # dir with WASMLD_HWJS_LLVM_BIN). Binaryen (wasm-opt/wasm-dis) is NOT part of # LLVM and is gone entirely — the coro arm never ran it, and the legacy Asyncify # arm that needed it is retired (see the bottom of file). HWJS_LLVM_BIN="$(hwjs_llvm_bin "$HWJS_HOME/libexec")" \ || { echo "wasmld: FATAL: pinned LLVM not found (set WASMLD_HWJS_LLVM_BIN, or build it per toolchain/llvm-from-source.md)." >&2; exit 1; } WASM_LD="$HWJS_LLVM_BIN/wasm-ld" # BRINTOS-WORKAROUND: brintos/hwjs-cc#64 revisit — this block IS the fix and lives on emc-dev, so it is not removed when the issue closes: when #64 closes, check that main answers both probes and drop this commit at the next emc-dev rebase. # Answer the two GNU-ld probes autoconf/libtool put to $LD. Neither is a link: # libtool builds shared libraries with `$CC -shared` and only asks the linker # what it IS. Left unanswered, _LT_LINKER_SHLIBS falls into its NON-GNU `linux*` # arm, whose only inner case is tcc, so it sets nothing at all -- archive_cmds # stays EMPTY while ld_shlibs keeps its initialised `yes`. libtool then reports # shared-library support, writes the .so version symlinks, and never runs a # command to create the file they name. That silence is the whole of hwjs-cc#64. # # -v / --version must carry "GNU" -> with_gnu_ld=yes # --help must carry ": supported targets: ... elf" -> ld_shlibs stays yes # # BOTH, or the GNU arm's own `$LD --help` gate sets ld_shlibs=no and there is # still no library -- loudly this time, but still none. # # The version phrase is upstream lld's own: it prints "(compatible with GNU # linkers)" for exactly this reason, and this fork's LLVM substitutes its # repository URL for it. The targets line is a compatibility declaration for # autoconf's host table, not a claim to emit ELF -- this linker emits wasm, and # the ELF-spelled options libtool generates once it believes us are consumed in # the argument loop below. # # Probes only: a real link always carries -o, and this never fires on one. # Answered before the environment guards below, which judge a link: an # installed toolchain's environment can hold link settings a bare probe does # not satisfy, and the probe would then die on them. _gnu_ld_probe=1 for a in "$@"; do case "$a" in -o|-o*) _gnu_ld_probe=0 ;; esac; done if [[ "$_gnu_ld_probe" == 1 ]]; then for a in "$@"; do case "$a" in -v|--version) _gnu_ld_v="$("$WASM_LD" --version 2>/dev/null | head -1)" echo "${_gnu_ld_v:-LLD} (compatible with GNU linkers)" exit 0 ;; --help) "$WASM_LD" --help echo "wasmld: supported targets: elf32-wasm32" exit 0 ;; esac done fi # Every compile this driver runs is a complete command line. An installed clang # can carry a config file holding the defaults of a per-file compile, and the # on-target toolchain's has -flto=full, so that `clang -c` writes bitcode. Read # here, it makes the merged-module compile write bitcode where the link takes # an object. HWJS_CLANG=( "$HWJS_LLVM_BIN/clang" --no-default-config ) # Defaults; users can override via env or extra args. INIT_PAGES="${WASMLD_INITIAL_PAGES:-256}" # 256 * 64 KiB = 16 MiB (holds the shadow stack + data + heap; the coro arm raises it again below for the .bss arenas) MAX_PAGES="${WASMLD_MAX_PAGES:-16384}" # 1 GiB max # FLAT RESUME DRIVE (drive_abi=3) is the CANONICAL userspace default (HWJS-3 # close): validated fast + correct + arbitrary depth with O(1) NATIVE/shadow # stack (recursion lives in the linear-memory frame arena, hwjs_user_rt.c §9). # Opt back to the nested drive (drive_abi=2, native nesting per level) with # HWJS_CORO_DRIVE_NESTED=1 (the same knob the flat-drive RED gate uses), or the # back-compat HWJS_CORO_DRIVE_FLAT=0. This selection is shared verbatim with # wasmcc (it picks the matching flat/nested crt) — keep them in sync. The KERNEL # is UNAFFECTED: it links via cc-wasm.sh, not this wrapper. # VALUE-keyed drive knobs (issue linux-in-the-browser#41): accepted values are 1 (on), # 0 (off), or unset/empty (default). The pass (HwjsCoroutinize envKnobBool) enforces the # same contract; refusing HERE too puts the refusal at the earliest vantage (before a # whole merge+link runs) and keeps the driver's own !=0 tests honest (a garbage value # must never silently select either drive). for _dk in HWJS_CORO_DRIVE_FLAT HWJS_CORO_DRIVE_NESTED; do case "${!_dk:-}" in ''|0|1) ;; *) echo "wasmld: FATAL: $_dk='${!_dk}' — this knob is VALUE-keyed (1 = on, 0 = off, unset/empty = default); refusing to guess (linux-in-the-browser#41)." >&2 exit 1 ;; esac done if [[ "${HWJS_CORO_DRIVE_NESTED:-0}" != "0" ]]; then HWJS_DRIVE_FLAT=0 else HWJS_DRIVE_FLAT="${HWJS_CORO_DRIVE_FLAT:-1}" # default 1 = flat fi # Shadow stack. The flat drive is O(1) native stack, so the userspace link no # longer needs the old 8 MiB deep-recursion STOPGAP (that covered the nested # drive's per-level native nesting). Flat default = 1 MiB (ample for the O(1) # driver loop + musl's non-coro native call chains; flat depth 1000/5000 lives # in the arena, not here). The nested opt-out keeps the 8 MiB (it still nests # natively per level). Env override (WASMLD_STACK) always wins; a too-small # initial-memory for the chosen stack is a LOUD wasm-ld "initial memory too # small" error, never a silent truncation. if [[ "$HWJS_DRIVE_FLAT" != "0" ]]; then STACK="${WASMLD_STACK:-1048576}" # 1 MiB (flat: O(1) native stack) else STACK="${WASMLD_STACK:-8388608}" # 8 MiB (nested opt-out: native deep recursion) fi ASYNCIFY="${WASMLD_ASYNCIFY:-1}" # 1 = run the Asyncify pass (D1-FORK; legacy arm only) FPCAST_EMU="${WASMLD_FPCAST_EMU:-0}" # 1 = prepend --fpcast-emu (D1-BASH; opt-in, bash only, legacy arm only) HWJS="${WASMLD_HWJS:-0}" # 1 = the brintium coro arm (HWJS-3) # DYNAMIC-MAIN model (HWJS-5 STEP 2, ADR-0004): a dlopen-using program is a # dynamic MAIN that IMPORTS the shared __indirect_function_table (env), so a # dlopen'd PIC side module (-shared) shares the SAME table — dlsym returns a # shared-table index the main call_indirects. ADDITIVE: default 0 keeps the # self-contained static image (bash and friends own their internal table). The # main itself is NOT PIC (only side modules are -shared/PIC); it just sources # its table from env instead of defining+exporting one. Memory is already # host-owned (--import-memory), so a host-owned table is the symmetric choice. DYNAMIC_MAIN="${WASMLD_DYNAMIC_MAIN:-0}" # 1 = dlopen-capable dynamic main (--import-table) # DYNAMIC-MODULE records (HWJS-5 F117): a dynamic module (the dlopen-capable # main + every dlopen'd .so) is built with HWJS_CORO_DYNAMIC_MODULE=1 so the # plugin emits the per-module F117 register ctors (__hwjs_suspends_register / # __hwjs_capsummary_register / __hwjs_fpcast_register, as applicable) + the weak # @__hwjs_module_id the host loader binds per instance, and switches open-world # consults to the runtime kernel registry (resolve -> proceed; unresolved -> # __hwjs_e8_refuse loud). OFF (default) = static/closed-world (bash/kernel/ # corpus): no records, the closed-world consult. Opt-in; never set for static. DYNAMIC_MODULE="${WASMLD_DYNAMIC_MODULE:-0}" # 1 = emit F117 per-module records # -shared SIDE-MODULE arm (HWJS-5 M1): the production path for building a # suspend-capable dlopen'd .so — PIC bitcode inputs, merged into ONE module, # ONE pass run under the dynamic-module env (F117 ctors + F118/F119/F121 # seams + flat drive + the single hwjs.abi manifest), then # `wasm-ld --experimental-pic -shared`. Detected from the command line; # implies WASMLD_DYNAMIC_MODULE=1 (a .so IS a dynamic module by definition). IS_SHARED=0 for _a in "$@"; do [[ "$_a" == "-shared" || "$_a" == "--shared" ]] && IS_SHARED=1 done # The wasm.linux.needed record a link writes. Version 2 names each library by # its soname, with the digest of the bytes linked against and the consumer's # view of the library's interface in parallel arrays, so a newer build of the # library under the same soname can still be bound (the loader checks the # view). Version 1, the digest-qualified file names, stays the default until # the layer that packages these modules reads version 2 and asks for it with # WASMLD_NEEDED_RECORD=2. NEEDED_RECORD_V=1 case "${WASMLD_NEEDED_RECORD:-1}" in 1) : ;; 2) NEEDED_RECORD_V=2 ;; *) echo "wasmld: FATAL: WASMLD_NEEDED_RECORD=${WASMLD_NEEDED_RECORD} -- the record versions are 1 and 2." >&2; exit 1 ;; esac # A -shared link's -soname/-h operand. wasm-ld has no such option; the name is # kept and written into the side module as wasm.linux.soname, the name a # consumer records it under. SONAME_ARG="" # The -Bsymbolic option a -shared link forwards to wasm-ld, or empty (the # argument loop sets it; see the -Bsymbolic arm there). BSYMBOLIC_FLAG="" # BRINTOS-1734-SHARED-BUILTINS: every -shared link needs the compiler-rt builtins TU, # not just the # libc.so producer — a side module's soft-float/wide-int calls are created during # CODEGEN, so they cannot bind to libc.so (which defines them but does not export # them: its surface is the explicit glibc Versions allowlist). if [[ $IS_SHARED == 1 ]]; then HWJS_LIBC_BUILTINS_BC="${WASMLD_HWJS_LIBC_BUILTINS_BC:-$HWJS_TOOLS_DIR/build/builtins-wasm32-pic.bc}" [[ -f "$HWJS_LIBC_BUILTINS_BC" ]] || { echo "wasmld: FATAL (-shared): no compiler-rt builtins TU at $HWJS_LIBC_BUILTINS_BC. A -shared link runs NO import-surface audit, so a missing TU would ship env.__addtf3-class imports SILENTLY and the loader would refuse the consumer main at dlopen. Build it ('make -C distros/common builtins-pic') or set WASMLD_HWJS_LIBC_BUILTINS_BC. (BRINTOS-1734)" >&2 exit 1 } fi if [[ $IS_SHARED == 1 && "$DYNAMIC_MODULE" == "0" ]]; then echo "wasmld: NOTE (-shared): implying WASMLD_DYNAMIC_MODULE=1 — a -shared side module is a dynamic module by definition (F117 records + the hwjs.abi manifest)." >&2 DYNAMIC_MODULE=1 fi # ── Dynamic-libc arms (PLAN-DYNAMIC-LIBC). # WASMLD_LIBC_SO=1 — the libc.so PRODUCER: a refinement of the -shared arm that (a) full-links the # WHOLE PIC bitcode pool ($WASMLD_HWJS_LIBC_BC_PIC) + the S2 TLS accessor TU (no need-only pull — # the closure IS the whole libc), (b) forwards HWJS_CORO_PUBLISH_SUSPENDERS so the ONE merged pass # run PUBLISHES the per-export suspend/native partition + stamps its sha256 into an hwjs.abi v2 # manifest, (c) cross-verifies the published verdicts against the final .so's name section, and # (d) installs the partition at WASMLD_LIBC_SO_PARTITION_OUT (required). # WASMLD_LIBC_IMPORT=1 — the MAIN consumer (mirrors the R4 WASMLD_RT_IMPORT shape): no musl pool pull # (libc refs become imports resolved from libc.so, module #1, at load); the merged-module codegen # flips -fno-pic → -fPIC and the final link swaps --allow-undefined → # --unresolved-symbols=import-dynamic (S5 mechanism (a′): undefined DATA becomes loader-provided # mutable GOT.mem. globals on a FIXED-LAYOUT main — no -pie, layout/exec/fork contract # unchanged); the published partition (WASMLD_HWJS_XMOD_SUSPENDERS= — a DELIBERATE lift of # the "misplaced request" guard below) seeds the import-suspend partition; the witness sanctions # env fns / GOT.* BY NAME from lists DERIVED from the built libc.so (WASMLD_LIBC_SO_PATH, required). LIBC_SO="${WASMLD_LIBC_SO:-0}" # 1 = libc.so producer refinement of -shared LIBC_IMPORT="${WASMLD_LIBC_IMPORT:-0}" # 1 = libc.so-importing dynamic MAIN # WASMLD_RT_SO=1 — the kernel-provided runtime module producer (PLAN-THREADS # §4 step 8): the ONE-TU hwjs_user_rt.c -shared link, in its status-channel # twin spelling (HWJS_STATUS_CHANNEL=1 [+ HWJS_RT_LANES]). An abi-4 caller # detects an imported leaf's park by the CHANNEL RAISE the leaf's own # emission performs — a flat-built runtime under an abi-4 main silently # transits every leaf park (set-over-set at the next park; witnessed live # on the first lane-stamped dynamic thr1). This arm satisfies the Track M # partition mandate by PUBLISHING the runtime's own partition # (WASMLD_RT_SO_PARTITION_OUT, required) — the honest per-op suspend # record — without the libc.so producer's pool/export machinery. RT_SO="${WASMLD_RT_SO:-0}" # Set by the -shared TLS census when an ordinary side module owns thread_local # state; never taken from the environment. SIDE_TLS=0 if [[ "$RT_SO" == "1" ]]; then if [[ $IS_SHARED != 1 ]]; then echo "wasmld: FATAL: WASMLD_RT_SO=1 without -shared — the runtime-module producer is a refinement of the -shared side-module arm (PLAN-THREADS §4 step 8)." >&2 exit 1 fi if [[ "$LIBC_SO" == "1" || "$LIBC_IMPORT" == "1" ]]; then echo "wasmld: FATAL: WASMLD_RT_SO=1 combined with WASMLD_LIBC_SO/WASMLD_LIBC_IMPORT — one link cannot be the runtime producer AND a libc producer/consumer." >&2 exit 1 fi if [[ -z "${WASMLD_RT_SO_PARTITION_OUT:-}" ]]; then echo "wasmld: FATAL: WASMLD_RT_SO=1 requires WASMLD_RT_SO_PARTITION_OUT= — the published per-op suspender partition is the mandatory Track M record on every status-channel dynamic link (I3)." >&2 exit 1 fi fi if [[ "$LIBC_SO" == "1" && "$LIBC_IMPORT" == "1" ]]; then echo "wasmld: FATAL: WASMLD_LIBC_SO=1 and WASMLD_LIBC_IMPORT=1 are BOTH set — one link cannot be the libc.so producer AND a libc.so-importing main (PLAN-DYNAMIC-LIBC)." >&2 exit 1 fi # WASMLD_SO_SUSPENDERS_OUT (section (10) below) is refused here, before the # link it would otherwise cost. A -r partial link publishes nothing and ignores it. _so_susp_reloc=0 for _a in "$@"; do [[ "$_a" == "-r" || "$_a" == "--relocatable" ]] && _so_susp_reloc=1 done if [[ -n "${WASMLD_SO_SUSPENDERS_OUT:-}" && $_so_susp_reloc != 1 ]]; then if [[ $IS_SHARED != 1 ]]; then echo "wasmld: FATAL: WASMLD_SO_SUSPENDERS_OUT on a link that is not -shared — a main publishes its coroutine exports through WASMLD_DYNMAIN_SUSPENDERS_OUT (BRINTOS-2323)." >&2 exit 1 fi if [[ "$LIBC_SO" == "1" || "$RT_SO" == "1" ]]; then echo "wasmld: FATAL: WASMLD_SO_SUSPENDERS_OUT on the libc.so or runtime producer link — those publish a verdict partition (WASMLD_LIBC_SO_PARTITION_OUT, WASMLD_RT_SO_PARTITION_OUT), not a names list." >&2 exit 1 fi fi if [[ "$LIBC_SO" == "1" && $IS_SHARED != 1 ]]; then echo "wasmld: FATAL: WASMLD_LIBC_SO=1 without -shared — the libc.so producer is a refinement of the -shared side-module arm (PIC whole-closure dylib), never a main link (PLAN-DYNAMIC-LIBC §3.1)." >&2 exit 1 fi if [[ "$LIBC_IMPORT" == "1" ]]; then if [[ $IS_SHARED == 1 ]]; then echo "wasmld: FATAL: WASMLD_LIBC_IMPORT=1 on a -shared link — a side module's libc imports bind through the loader's needed-graph, not through the main consumer arm (PLAN-DYNAMIC-LIBC; use WASMLD_HWJS_XMOD_PARTITION_LIBC for a third .so consuming libc.so's published partition)." >&2 exit 1 fi if [[ "$DYNAMIC_MAIN" == "0" ]]; then echo "wasmld: FATAL: WASMLD_LIBC_IMPORT=1 requires WASMLD_DYNAMIC_MAIN=1 — a libc.so-importing main is a dynamic main by definition (imports the shared table; the loader binds module #1). Mirror of the WASMLD_RT_IMPORT guard (wasmcc)." >&2 exit 1 fi if [[ "$DYNAMIC_MODULE" == "0" ]]; then echo "wasmld: NOTE (WASMLD_LIBC_IMPORT): implying WASMLD_DYNAMIC_MODULE=1 — a libc.so-importing main is a dynamic module (F117 records + hwjs.abi manifest + the partition-keyed import-suspend seam)." >&2 DYNAMIC_MODULE=1 fi fi # WASMLD_NEEDED_LIBS=[:...] — the NON-LIBC half of the needed-list # (PLAN-DYNAMIC-LIBC §3.4 D4, generalised). Each path names an already-built side # module this main records a needed-entry for; the loader finds it by the # digest-qualified name on the kernel's search path and instantiates it before the # main, then binds the main's env fn imports from its exports. libc.so keeps its own # dedicated arm: it is module #1 by construction and carries the partition digest # lockstep no other library has, so it is never spelled through this knob. NEEDED_LIBS_RAW="${WASMLD_NEEDED_LIBS:-}" if [[ -n "$NEEDED_LIBS_RAW" && "$LIBC_IMPORT" != "1" ]]; then echo "wasmld: FATAL: WASMLD_NEEDED_LIBS is set on a link that is not the dynamic-main consumer arm (WASMLD_LIBC_IMPORT=1) — the needed-list rides ONE carrier appended by that arm, and an image that does not import libc.so is one the loader walks no graph for." >&2 exit 1 fi # BRINTOS-884: whether `-lNAME` may resolve to lib.so. # # ON for the dynamic-main consumer arm AND for a -shared side module. A static # link cannot consume a .so at all (wasm-ld refuses one by name), so it stays # off there and `-lNAME` keeps resolving to lib.a exactly as before, # which is what makes this change inert on the static distro. # # The -shared arm RESOLVES but does not RECORD: a side module carries no needed # list of its own (§3.4 single-carrier), so resolve_dash_l DROPS the hit and # leaves the symbol undefined for the loader to bind. Without the arm in this # gate that branch is unreachable, and a -shared link against a CONVERTED # dependency — whose .a no longer exists — dies on the .a search instead. # # WASMLD_DASH_L_STATIC=1 forces the old behaviour back on the dynamic arm — the # `-Bstatic` of this driver, for a caller that wants the archive even where a # shared object is on the path. It is an escape hatch, not a build posture: a # main that takes the archive carries the library's bytes and de-duplicates # nothing, which is the whole point of the migration. DASH_L_PREFERS_SHARED=0 # BRINTOS-1415 fixed a library consuming another library BY PATH; -lNAME was # never covered, because this gate excluded the -shared arm entirely. Once a # dependency converts, its .a is gone, so `-ltalloc` on a -shared link found # nothing and libtevent died. Both arms may now RESOLVE a .so; what they DO # with it differs, below. if [[ ( "$LIBC_IMPORT" == "1" || $IS_SHARED == 1 ) && "${WASMLD_DASH_L_STATIC:-0}" != "1" ]]; then DASH_L_PREFERS_SHARED=1 fi # Coro-arm toolchain surfaces (HWJS-3; same pin discipline as cc-wasm.sh). # HWJS_LLVM_BIN is defined at the top of the file (the WASM_LD default # rides it too). HWJS_NM/HWJS_AR default into the toolchains build, never # emsdk; their explicit override knobs still win. HWJS_PLUGIN="${WASMLD_HWJS_PLUGIN:-$HWJS_PLUGIN_HOME/HwjsCoroutinize.so}" # Track E pre-lowering plugin (PLAN-CXX-STATUS-CHANNEL §5.1; STATUS-CHANNEL-CONTRACT §3/§5.2): # HwjsEHPreLower — invoke → call + status check, landingpad/cleanup → ordinary blocks, # resume → return-UNWINDING. Loaded ONLY when the status-channel world is requested # (HWJS_STATUS_CHANNEL=1, or the pass's own HWJS_EH_PRELOWER=1 force-on); with both # unset/0 the plugin is not loaded; native EH is discarded before coroutinizing. HWJS_PRELOWER_PLUGIN="${WASMLD_HWJS_PRELOWER_PLUGIN:-$HWJS_PLUGIN_HOME/HwjsEHPreLower.so}" # Park-exit return-attribute truth plugin (the operator-new unreachable class, # 2026-07-23): HwjsRetAttrTruth — strips frontend RETURN-VALUE attrs # (noundef/nonnull/noalias/dereferenceable*/align/range/nofpclass) from # converted (presplitcoroutine) functions + their direct call sites, loaded # AFTER HwjsCoroutinize so it sees the converted module at PipelineStartEP # before default. Without it, a converted function whose frontend stamped # noundef+nonnull on the return (libc++abi's _Znwm) has its freeze(poison) # park exit folded to `unreachable` by the O2 pipeline — any park inside it # traps the lane (measured: the musl-dynamic thrstress churn trap). Loaded # under the SAME condition as the pre-lowering (the status-channel world is # where park exits return freeze(poison)); byte-identical otherwise. HWJS_RETTRUTH_PLUGIN="${WASMLD_HWJS_RETTRUTH_PLUGIN:-$HWJS_PLUGIN_HOME/HwjsRetAttrTruth.so}" # Opt-in null-page check: HwjsNullCheck, loaded FIRST and only under WASMLD_HWJS_NULL_CHECK=1. HWJS_NULLCHECK_PLUGIN="${WASMLD_HWJS_NULLCHECK_PLUGIN:-$HWJS_PLUGIN_HOME/HwjsNullCheck.so}" HWJS_LIBC_BC="${WASMLD_HWJS_LIBC_BC:-$HWJS_TOOLS_DIR/build/musl-bc}" # COMPILE triple of the program bitcode (BrintOS hwjs vendor). wasmcc/wasmcc-glibc # export this so the helper bitcode wasmld synthesizes below (abi_keepalive.c, # main_bridge.c) — and the ONE plugin compile of the merged module — is stamped # with the SAME triple the program TUs carry. Matching triples make llvm-link (and # the plugin compile of merged.bc) see a single triple, so the "Linking two modules # of different target triples" warning never fires. Default = the musl compile # triple; the glibc arm exports wasm32-hwjs-linux-gnu. (The final wasm-ld stage # takes no --target — a wasm object's OS field is irrelevant to the linker.) if [[ $IS_SHARED == 1 ]]; then # A side module is libc-less PIC code: default to the plain LINK triple # (the fixture recipe's --target=wasm32-hwjs-unknown). A caller that # compiled its TUs under a -linux triple (e.g. through wasmcc, which # exports WASMLD_HWJS_COMPILE_TARGET) keeps its own triple. HWJS_COMPILE_TARGET="${WASMLD_HWJS_COMPILE_TARGET:-wasm32-hwjs-unknown}" else HWJS_COMPILE_TARGET="${WASMLD_HWJS_COMPILE_TARGET:-wasm32-hwjs-linux-musl}" fi # NON-PIC MERGED IMAGE. The whole-program main image wasmld emits is ALWAYS # non-PIC (see the DYNAMIC-MAIN note below: "the main itself is NOT PIC; only # dlopen'd side modules are -shared/PIC"). This is independent of the per-TU PIC # level of the inputs — the musl pool is non-PIC and the glibc pool is PIC IR, but # BOTH link into a non-PIC main. It also MUST be non-PIC because the crt/glibc # reference linker-synthesized bounds (__init_array_start/end, __fini_array_*) # that are undefined at this compile: non-PIC emits absolute relocs wasm-ld can # resolve, whereas PIC emits R_WASM_MEMORY_ADDR_REL_SLEB against those undefined # symbols and the link fails. The *-linux compile triple defaults to PIC, so force # it off here for the synthesized helpers + the merged-module codegen. HWJS_PIC_ARGS=( -fno-pic -fno-PIE ) # Dynamic-libc consumer arm (S5 mechanism (a′), PLAN-DYNAMIC-LIBC §3.4): the ONE merged-module plugin compile # flips to -fPIC so genuinely-undefined DATA lowers to GOT-based access (loader-provided mutable # GOT.mem. globals under --unresolved-symbols=import-dynamic below). The main stays FIXED-LAYOUT # (no -pie at link): layout/exec-header/brk/fork contract unchanged. Because its base is fixed (memory # 0, table 1), -wasm-fixed-layout-pic addresses everything a compile DEFINES absolutely, as the # non-PIC main does: without it each access to the main's own data or function addresses pays a # global.get of a constant __memory_base/__table_base (or an internalized GOT.data.internal.) # plus an add (brintium#88). Symbols undefined at that compile still go through the GOT, which on a # split link includes what another piece defines (correct, via lld's internal GOT entry). The # __init_array_start REL_SLEB concern in the comment above did not reproduce on the musl shape (S5 §4 # — those symbols are defined at the final link); the glibc arm re-audits it. if [[ "$LIBC_IMPORT" == "1" ]]; then HWJS_PIC_ARGS=( -fPIC -mllvm -wasm-fixed-layout-pic ) fi # ── The final link_coro undefined-symbol policy ────────────────────────────────────────────── # # --allow-undefined IS NOT ONE POLICY, IT IS TWO. lld spells it out (Driver.cpp:865-870): # # // Legacy --allow-undefined flag which is equivalent to # // --unresolve-symbols=ignore + --import-undefined # # and those two halves cover DISJOINT symbol classes, with opposite consequences: # # --import-undefined turns an undefined FUNCTION into an env. import. The # symbol is then VISIBLE in the finished module's import section, # and the PHANTOM-IMPORT witness below judges every one of them # against the sanctioned surface. A guest that references a # function nobody defines therefore already fails the LINK. # --unresolved-symbols=ignore additionally swallows undefined DATA. lld emits an # i32.const 0 for the address and says nothing. Nothing is added # to the import section, so NO post-link witness can see it — # the module is indistinguishable from one where the author # genuinely wrote a null pointer. This is the class that shipped # `cpuinfo_op` bound to address 0 in vmlinux and took the machine # down through a call_indirect on a null ->start. # # SO THE STATIC ARM TAKES THE FIRST HALF ONLY. Undefined data becomes `wasm-ld: error: : # undefined symbol: ` — refused at the link, named, on the arm that ships. Everything else is # bit-for-bit what it was: an undefined function still imports, a WEAK undefined datum still # resolves to 0 (the ELF semantics a guest author expects from `extern __attribute__((weak))`, which # --unresolved-symbols=import-dynamic would instead have broken with a REL-reloc error). # # THE CONFTEST-PROBE FLOW IS UNAFFECTED, AND THAT IS A MEASURED CLAIM, NOT A HOPE. autoconf probes # feature availability by LINKING a program against a declared-but-maybe-absent symbol and reading # the exit status. Those probes are function probes (AC_CHECK_FUNCS / AC_CHECK_LIB / AC_SEARCH_LIBS # all emit `char f(); ... f();`), and their fate is UNCHANGED here: they still link to an env import # and are still refused by the phantom-import witness, which is a non-zero exit exactly as before. # The handful of DATA probes autoconf does emit (tzname, sys_siglist, program_invocation_name…) were # answered "yes, and the address is 0" under the old flag — a FALSE YES that made the package # compile a reference to address 0 into its shipped binary. They now answer "no" and the package # takes its fallback. There is no probe-vs-image discriminator here because there is nothing to # discriminate: a link that binds a datum to 0 is wrong in a probe and wrong in an image, and the # probe's own contract (non-zero exit = feature absent) is satisfied by the refusal. # # THE ONE THING --import-undefined DOES NOT COVER: an undefined wasm GLOBAL (addrspace(1)). lld's # allowUndefined() tests `isa(sym) && ctx.arg.importUndefined`, so a global is # neither imported nor ignored — it is a hard error. But an undefined global is in the SAME # visibility class as an undefined function (it becomes env.:global in the import section and # the phantom-import witness judges it), not in the invisible class we are closing. The pass creates # exactly this shape — EHPreLowerPass's `__hwjs_status_channel_addr`, an external i32 addrspace(1) # GlobalVariable — and it CANNOT declare its own import at the definition site the way # hwjs_user_rt.c's linux.syscall does, because clang's import_module/import_name attributes are # Function-only and WebAssemblyAsmPrinter emits them only for Functions. So wasmld re-derives the # sanction from the LINK INPUTS' OWN SYMBOL TABLES at every link — undefined symbols of Type GLOBAL, # read out of the objects being linked (derive_undef_global_allow below) — and hands lld that list # via --allow-undefined-file=. No name is written down anywhere; a new host global is sanctioned by # existing, and a DATA symbol can never enter the set because it is a different Type. # # The consumer arm keeps --unresolved-symbols=import-dynamic — S5's exact spelling: there, undefined # data BECOMES a GOT.mem import (loud at load, witness-fatal at link) because that arm is -fPIC and # a loader really is going to bind it. NEVER append one flag to the other: with both # --allow-undefined and --unresolved-symbols=* present --allow-undefined unconditionally wins # regardless of order (lld Driver.cpp:865-870) — the exclusivity assertion before the final link # refuses that line. CORO_UNDEF_FLAG=( --import-undefined ) # --experimental-pic only silences lld's "dynamic imports are not yet stable" warning, which a # caller's -Wl,--fatal-warnings (meson's link-argument checks) turns into a failed link. [[ "$LIBC_IMPORT" == "1" ]] && CORO_UNDEF_FLAG=( --unresolved-symbols=import-dynamic --experimental-pic ) # RED KNOB — the ONE token that puts the address-0 data bind back, for the gate that proves this # refusal is load-bearing. A gate whose subject row merely says "the link failed" cannot tell a # working tripwire from a broken toolchain; the RED row re-links the SAME object with the SAME # driver under this token and requires it to SUCCEED, and requires the produced module to carry NO # import for the missing datum — the invisibility that is the whole defect. It is arm-owned (the # caller-supplied spelling stays a refusal), it is spelled with RED in its name so no build script # can reach for it as a workaround, and every link that consults it says so on stderr, so an image # built under it is never mistaken for a normally-linked one. # Gate: distros/linux-6.12-musl-busybox/tools/run-guestundef-gate.mjs. if [[ "${WASMLD_RED_ALLOW_UNDEFINED_DATA:-0}" == "1" ]]; then CORO_UNDEF_FLAG=( --allow-undefined ) echo "wasmld: NOTE (RED WASMLD_RED_ALLOW_UNDEFINED_DATA=1): undefined-symbol policy forced back to --allow-undefined — undefined DATA will bind SILENTLY to address 0 and emit no import. This is the gate's RED arm, never a build posture." >&2 fi HWJS_NM="${WASMLD_HWJS_NM:-$HWJS_LLVM_BIN/llvm-nm}" # reads pinned-22 bitcode symbols (scan-proven) HWJS_AR="${WASMLD_HWJS_AR:-$HWJS_LLVM_BIN/llvm-ar}" HWJS_OBJDUMP="${WASMLD_HWJS_OBJDUMP:-$HWJS_LLVM_BIN/llvm-objdump}" # PREEMPTIBILITY native-input loop scan HWJS_READOBJ="${WASMLD_HWJS_READOBJ:-$HWJS_LLVM_BIN/llvm-readobj}" # undefined-GLOBAL sanction derivation # LLVM-NM SIGNAL GUARD # # Every llvm-nm run goes through hwjs_nm. Most callers read its output with # `2>/dev/null || true`, so an llvm-nm that dies on a signal would hand them an # empty listing, and the decision taken on it would be taken on no data. An exit # at or above 128 stops the link at the call instead. The call is usually inside # $(...) or a pipeline, where exit leaves only the subshell, so the guard also # signals the driver itself, and writes to the stderr the driver started with: # the caller's own stderr is often /dev/null. exec {HWJS_NM_ERR_FD}>&2 trap 'BRINTLD_USR1=1; exit 1' USR1 hwjs_nm() { local _nm_rc=0 _nm_i=0 "$HWJS_NM" "$@" || _nm_rc=$? (( _nm_rc >= 128 )) || return "$_nm_rc" while [[ "${FUNCNAME[_nm_i+1]:-}" == run_llvm_bulk ]]; do _nm_i=$((_nm_i + 1)); done echo "wasmld: FATAL (llvm-nm): '$HWJS_NM' exited $_nm_rc (signal $((_nm_rc - 128))) at brintld line ${BASH_LINENO[_nm_i]} (${FUNCNAME[_nm_i+1]:-main}). Its listing is not a symbol list; refusing rather than deciding on it." >&"$HWJS_NM_ERR_FD" [[ "$BASHPID" == "$$" ]] || kill -s USR1 "$$" exit 1 } # End of the llvm-nm signal guard. # Internal variable-size LLVM commands must not put an archive's member list # back into exec's bounded argv block. This is the GNU response encoding used # by brint-tool's SymbolResponseFile: quote every argument, escaping only '\' # and '"'. Bash %q is NOT LLVM's response syntax. These internal tools use the # POSIX GNU tokenizer; wasm-ld's caller-selected quoting policy is separate. # No helper subprocess receives the expanded list. Keep one ordered tool run # (not chunked links, which change member/override semantics), and preserve its # failure status. Callers retain their existing diagnostics and post-gates. # Once the link has its own directory, LLVM_BULK_DIR names it and the response # file is named there by the shell's pid and a count, and goes with the # directory: no mktemp and no rm. The pid keeps two subshells apart, which do # not see each other's count. declare +x LLVM_BULK_DIR="" LLVM_BULK_SEQ=0 run_llvm_bulk() { local _bulk_tool="$1" _bulk_rsp _bulk_arg _bulk_status=0 _bulk_own=0 shift if [[ -n "${LLVM_BULK_DIR:-}" ]]; then LLVM_BULK_SEQ=$(( ${LLVM_BULK_SEQ:-0} + 1 )) _bulk_rsp="$LLVM_BULK_DIR/brintld-llvm.$BASHPID.$LLVM_BULK_SEQ" _bulk_own=1 else _bulk_rsp="$(mktemp "${WORK:-${TMPDIR:-/tmp}}/brintld-llvm.XXXXXX")" || { echo "brintld: cannot create internal LLVM response file for '$_bulk_tool'" >&2 return 1 } fi if ! { for _bulk_arg in "$@"; do # LLVM's GNU tokenizer drops empty quoted tokens. None of these internal # filename/option lists permits one: refuse instead of silently omitting it. if [[ -z "$_bulk_arg" ]]; then echo "brintld: empty internal LLVM argument for '$_bulk_tool'" >&2 _bulk_status=1 break fi _bulk_arg="${_bulk_arg//\\/\\\\}" _bulk_arg="${_bulk_arg//\"/\\\"}" printf '"%s"\n' "$_bulk_arg" || { _bulk_status=1; break; } done [[ $_bulk_status == 0 ]] } > "$_bulk_rsp"; then echo "brintld: cannot encode internal LLVM response file for '$_bulk_tool'" >&2 _bulk_status=1 fi if [[ $_bulk_status == 0 ]]; then if "$_bulk_tool" "@$_bulk_rsp"; then :; else _bulk_status=$?; fi fi if [[ $_bulk_own == 0 ]] && ! rm -f -- "$_bulk_rsp"; then echo "brintld: cannot remove internal LLVM response file '$_bulk_rsp'" >&2 [[ $_bulk_status != 0 ]] || _bulk_status=1 fi return "$_bulk_status" } # End internal LLVM response transport. # derive_section_bounds # # A weak undefined __start_/__stop_ whose section no input defines is 0 on ELF, and # the code that walks such a section tests the bound before it walks. On the import-dynamic arm # lld instead keeps the symbol preemptible and turns every reference into a GOT.mem import, # which no library can answer: the bounds are lld-synthesized per module, so the witness refuses # them. A HIDDEN weak undefined symbol is not preemptible, and lld gives its GOT entry an # internal global set to 0. lld takes the flags of the last weak undefined reference it reads, # so the object written here, linked after every input, carries one hidden weak reference per # bound the inputs reference weak and undefined. A defined section still gets its real bounds, # and a strong reference is left as it is. derive_section_bounds() { local out="$1"; shift local -a objs=() local a for a in "$@"; do [[ "$a" == -* ]] && continue [[ -f "$a" ]] || continue case "$a" in *.o|*.a|*.obj) objs+=( "$a" ) ;; esac done [[ ${#objs[@]} -gt 0 ]] || return 1 local syms names syms="$(run_llvm_bulk "$HWJS_READOBJ" --symbols "${objs[@]}" 2>/dev/null)" \ || fatal "llvm-readobj could not read the symbol tables of the final link inputs [${objs[*]}], so the weak section bounds cannot be derived. Refusing rather than guessing." names="$(awk ' /^[[:space:]]*Symbol \{/ { name=""; type=""; undef=0; weak=0; next } /^[[:space:]]*Name:/ { name=$2; next } /^[[:space:]]*Type:/ { type=$2; next } /UNDEFINED/ { undef=1; next } /BINDING_WEAK/ { weak=1; next } /^[[:space:]]*\}/ { if (type == "DATA" && undef && weak && name ~ /^__(start|stop)_[A-Za-z_][A-Za-z0-9_]*$/) print name; name=""; type=""; undef=0; weak=0 } ' <<<"$syms" | LC_ALL=C sort -u)" [[ -n "$names" ]] || return 1 local src="${out%.o}.c" n i=0 : > "$src" for n in $names; do printf 'extern const char %s[] __attribute__((weak, visibility("hidden")));\n' "$n" >> "$src" printf '__attribute__((used)) static const void *const __brintld_bound_%d = %s;\n' "$i" "$n" >> "$src" i=$((i + 1)) done "${HWJS_CLANG[@]}" --target="$HWJS_COMPILE_TARGET" -O2 \ -matomics -mbulk-memory -mmutable-globals -msign-ext \ -c "$src" -o "$out" 2>"${out%.o}.err" \ || { cat "${out%.o}.err" >&2; fatal "the weak section-bound object [$(tr '\n' ' ' <<<"$names")] failed to compile (error above)."; } echo "wasmld: NOTE (SECTION BOUNDS): weak undefined section bound(s) [$(tr '\n' ' ' <<<"$names")] are linked hidden: a bound whose section no input defines is 0, as on ELF, not a GOT.mem import." >&2 } # derive_undef_global_allow # # Writes the newline-separated names of every symbol that is UNDEFINED and of Type GLOBAL in the # objects/archives on this link line. That set — and nothing else — is what --allow-undefined-file= # sanctions, so the static arm's undefined-symbol policy stays "functions import, globals import, # data is a link error" without a single symbol name living in this file. # # Read from the INPUTS, not from a policy: the same argv the linker is about to consume, at the same # moment, so a set that drifted would have to drift from the objects themselves. A name that is # undefined-DATA anywhere on the line is REFUSED rather than sanctioned even if some other object # declares it a global — a kind collision is exactly the ambiguity this must not resolve silently. derive_undef_global_allow() { local out="$1"; shift local -a objs=() local a for a in "$@"; do [[ "$a" == -* ]] && continue [[ -f "$a" ]] || continue case "$a" in *.o|*.a|*.obj) objs+=( "$a" ) ;; esac done : > "$out" [[ ${#objs[@]} -gt 0 ]] || return 0 [[ -x "$HWJS_READOBJ" ]] \ || fatal "the undefined-GLOBAL sanction is DERIVED from the link inputs' symbol tables, and llvm-readobj ('$HWJS_READOBJ') is not executable — so the set cannot be derived. Refusing rather than falling back to --allow-undefined, which would silently re-open the address-0 data bind (point WASMLD_HWJS_READOBJ at the pinned llvm-readobj)." local syms syms="$(run_llvm_bulk "$HWJS_READOBJ" --symbols "${objs[@]}" 2>/dev/null)" \ || fatal "llvm-readobj could not read the symbol tables of the final link inputs [${objs[*]}], so the undefined-GLOBAL sanction cannot be derived. Refusing rather than guessing." # One record per `Symbol { … }` block: Name, Type, and whether UNDEFINED appears in its Flags. local pairs pairs="$(awk ' /^[[:space:]]*Symbol \{/ { name=""; type=""; undef=0; next } /^[[:space:]]*Name:/ { name=$2; next } /^[[:space:]]*Type:/ { type=$2; next } /UNDEFINED/ { undef=1; next } /^[[:space:]]*\}/ { if (name != "" && undef) print type "\t" name; name=""; type=""; undef=0 } ' <<<"$syms" | LC_ALL=C sort -u)" local globals datas collide globals="$(awk -F'\t' '$1=="GLOBAL"{print $2}' <<<"$pairs" | LC_ALL=C sort -u)" datas="$(awk -F'\t' '$1=="DATA"{print $2}' <<<"$pairs" | LC_ALL=C sort -u)" if [[ -n "$globals" && -n "$datas" ]]; then collide="$(LC_ALL=C comm -12 <(printf '%s\n' "$globals") <(printf '%s\n' "$datas") || true)" [[ -z "$collide" ]] \ || fatal "KIND COLLISION on the final link line: [$(tr '\n' ' ' <<<"$collide")] is undefined as BOTH a wasm GLOBAL and a DATA symbol across the inputs. Sanctioning it as a global would let the data reference bind to address 0 under cover of the global's import; refusing it as data would break the global's host binding. Neither is decidable here, so this is a refusal: make the two references agree on what the symbol is." fi [[ -z "$globals" ]] || printf '%s\n' "$globals" > "$out" } # NEEDED LIBRARY POSITIONS. A compiler driver resolves each shared library on # a dynamic main's line itself and hands it over in WASMLD_NEEDED_LIBS, leaving # --brint-needed-at= where it stood. NEEDED_SO_POS[k] is the count of # archive members (POOL) before entry k's first mention, or "" for an entry the # line never names (the caller's own WASMLD_NEEDED_LIBS), read as 0. # Test: test/pool-needed-so-exports.sh. # needed_so_place : entry stands here on the line; the first # mention counts, as on GNU ld. needed_so_place() { local _np_at=${#POOL[@]} if [[ -z "${NEEDED_SO_POS[$1]}" || ${NEEDED_SO_POS[$1]} -gt $_np_at ]]; then NEEDED_SO_POS[$1]=$_np_at fi } # needed_at_marker : place the needed entry a --brint-needed-at= marker names. needed_at_marker() { local _nat_real _nat_j _nat_real="$("$BRINT_TOOL" realpath "${1#--brint-needed-at=}")" \ || fatal "'$1': the needed library it marks does not resolve to a real file (its reason above)." for ((_nat_j = 0; _nat_j < ${#NEEDED_SO_REALS[@]}; _nat_j++)); do if [[ "${NEEDED_SO_REALS[$_nat_j]}" == "$_nat_real" ]]; then needed_so_place "$_nat_j" return 0 fi done echo "wasmld: NOTE ('$1'): the marked library is not in this link's needed list; the marker is dropped." >&2 } # pool_provided_write : `POS NAME` for every function and global the # direct needed entries export, POS the entry's position (the lowest when two # export one name). Names the loader keeps per module (__-reserved, except the # C++ ABI runtime) are left out. pool_provided_write() { local _pp_i _pp_so : > "$1.exports" for ((_pp_i = 0; _pp_i < NEEDED_SO_DIRECT_N; _pp_i++)); do _pp_so="${NEEDED_SO_SNAPSHOTS[$_pp_i]}" "$BRINT_TOOL" exports "$_pp_so" --with-kind > "$1.one" \ || fatal "archive pull: brint-tool cannot read the exports of needed library ${NEEDED_SO_NAMES[$_pp_i]%.*} (its reason above)." awk -v pos="${NEEDED_SO_POS[$_pp_i]:-0}" '{ print pos, $0 }' "$1.one" >> "$1.exports" done awk '($2 == "function" || $2 == "global") { n = $3 if (n ~ /^__/ && n !~ /^__cxa_/ && n != "__dynamic_cast" && n !~ /^__gxx_personality/) next if (!(n in at) || $1 + 0 < at[n]) at[n] = $1 + 0 } END { for (n in at) print at[n], n }' "$1.exports" \ | LC_ALL=C sort -k2,2 > "$1" } # Find the -o (or -o) the caller requested so we can # link to a temporary and post-process into the final path. OUT="" args=("$@") for ((i = 0; i < ${#args[@]}; i++)); do a="${args[$i]}" if [[ "$a" == "-o" ]]; then OUT="${args[$((i + 1))]}" break elif [[ "$a" == -o* ]]; then OUT="${a#-o}" break fi done BRINTLD_OUT="$OUT" # The image is linked, checked and rewritten in place several times before it is # done, so a reader of -o could see it half-written, and a refusal removes what # is there. Two links that name the same -o run at once when a make rule lists # several targets and its recipe writes all of them: make -j runs that recipe # once per target. Each link therefore writes into a new directory of its own # beside -o, under the output's own basename (wasm-ld writes the basename into # the name section, and the DWARF twin check compares it), and renames the # finished image to -o, the way wasm-ld itself replaces its output. Whichever # link renames last wins, and every reader sees one whole image. brintld_stage_out() { local d b s i [[ -n "$OUT" && -z "$BRINTLD_OUT_STAGE" ]] || return 0 # Not a regular file (/dev/null, a FIFO): written in place, as before. [[ ! -e "$OUT" || -f "$OUT" ]] || return 0 b="${OUT##*/}" [[ -n "$b" && "$b" != . && "$b" != .. ]] || return 0 d=. [[ "$OUT" != */* ]] || d="${OUT%/*}" [[ -n "$d" ]] || d=/ for i in 1 2 3 4 5 6 7 8; do s="$d/.$b.brintld.$$.$RANDOM" if mkdir -m 700 -- "$s" 2>/dev/null; then BRINTLD_OUT_STAGE="$s" OUT="$s/$b" return 0 fi done fatal "cannot create a directory beside '$BRINTLD_OUT' to write the image in (last tried '$s')." } # The finished image (and its owner-audit sidecar first, so an image at -o has # its sidecar) goes to -o; from here on OUT is -o again. brintld_place_out() { [[ -n "$BRINTLD_OUT_STAGE" && "$OUT" != "$BRINTLD_OUT" ]] || return 0 if [[ -f "$OUT.export-owners" ]]; then mv -f -- "$OUT.export-owners" "$BRINTLD_OUT.export-owners" \ || fatal "cannot install the owner-audit sidecar at '$BRINTLD_OUT.export-owners'." fi if [[ -e "$OUT" ]]; then mv -f -- "$OUT" "$BRINTLD_OUT" || fatal "cannot rename the finished image to '$BRINTLD_OUT'." fi OUT="$BRINTLD_OUT" } # Force-exported process ABI. _start + __wasm32_child_return + the asyncify/ # args buffers were always here; the tls/stack/entry/signal half was added at # D1-BASH.c (blocker 2). All come from wasm_thread.S / crt1_musl.c, which are # linked into EVERY image, so each --export always resolves and survives # --gc-sections. Forcing them here makes the HardwareJS process ABI a LINKER # INVARIANT instead of a per-target opt-in: the spawn handler dispatches # __wasm32_user_entry, and fork-resume needs {get,set}_tls_base so the child # can restore __tls_base (without it musl __post_Fork's __pthread_self() derefs # a near-null pointer and the child OOBs before any user code). bash's # generated link bypassed the tools-Makefile per-target --export list, dropping # these and crashing every bash fork (subshell/pipe/&) in the child. The # tools-Makefile's 7x per-target repetition can later collapse onto this default. link() { "$WASM_LD" \ --no-entry \ --export=_start \ --export=__wasm32_child_return \ --export=__wasm32_asyncify_buf_addr \ --export=__wasm32_asyncify_buf_size \ --export=__wasm32_args_buf_addr \ --export=__wasm32_args_buf_size \ --export=__wasm32_get_tls_base \ --export=__wasm32_set_tls_base \ --export=__wasm32_get_stack_pointer \ --export=__wasm32_set_stack_pointer \ --export=__wasm32_user_entry \ --export=__wasm32_set_signal_region \ --export=__heap_base \ --export=__data_end \ --export=__wasm_call_ctors \ --allow-undefined \ --import-memory=env,user_memory \ --shared-memory \ --initial-memory=$((INIT_PAGES * 65536)) \ --max-memory=$((MAX_PAGES * 65536)) \ -z stack-size=$STACK \ --gc-sections \ "$@" } # Coro-arm final link: the asyncify buffer accessors no longer exist # (compiled out of the coro crt — they would be --export hard errors), and # the hwjs drive/witness surface is force-exported instead: # - hwjs_resume/done/destroy (hwjs_user_thunks.o) + __hwjs_take_parked # (rt TU; also auto-exported via export_name — listed for invariance): # the worker.mjs pump's drive ops (design §4), # - the per-thread protocol slots (parked pair, park reason/result, the # arena census, the violation witness) are NOT exported data any more: # they are fields of each thread's runtime block (hwjs_user_rt.c, struct # hwjs_tcb), and the host reads them at block + the offsets the # runtime's self-exporting op __hwjs_tcb_field answers. Until 2026-10-10 # they were per-lane arrays exported under their lane-0 alias names # (__hwjs_parked, __hwjs_park_reason, __hwjs_frame_live, ...), and the # host indexed them by lane. # - __hwjs_promise_i32 export-if-defined: pass-emitted reader, present # only when some natural i32 return rides a promise slot. # §3.5 (PLAN-DYNAMIC-LIBC): the force-export block is a FILE-LEVEL ARRAY so the # WASMLD_LIBC_IMPORT=1 arm can run the force-export OWNER AUDIT over it and substitute the audited # list (owner=main kept; owner=libc.so dropped — the host looks those up on module #1; owner=rt # dropped under WASMLD_RT_IMPORT — module #0; a symbol NO side owns is a loud refusal at the audit). # --export-if-defined entries pass through unaudited (if-defined cannot mis-fire). CORO_EXPORT_SURFACE=( --export=_start --export=__wasm32_args_buf_addr --export=__wasm32_args_buf_size --export=__wasm32_get_tls_base --export=__wasm32_set_tls_base --export=__wasm32_get_tls_size --export=__wasm32_get_tls_align --export-if-defined=__wasm_init_tls --export=__wasm32_get_stack_pointer --export=__wasm32_set_stack_pointer --export=__wasm32_user_entry --export=__wasm32_set_signal_region --export=__heap_base --export=__data_end --export=__wasm_call_ctors --export-if-defined=__wasm32_ctors_run_in_start # The constructors' other half. musl's crt1_musl.c exports the marker above, so the host skips its # own __wasm_call_ctors() and the constructors run from _init(), which musl's libc_start_init calls. # In a dynamic main that call is in libc.so, through its env._init import, and with the main not # exporting _init the host bound libc.so's own empty one: no global constructor in the main ever ran, # nor the atexit destructors they register. std::cout was never constructed, and the first write to # it trapped out of bounds in its sentry; 12 call-cxx cases on a musl dynamic main. A static main's # libc_start_init calls the crt's _init directly, and exporting it there changes nothing. glibc's # libc.so imports no _init (its crt runs the constructors from a main wrapper). --export-if-defined=_init --export=hwjs_resume --export=hwjs_done --export=hwjs_destroy --export=__hwjs_take_parked # The two pass-emitted BUDGET handlers: the M6 startup sanity trap and the # safepoint expiry arm. CoroutinizePass emits each as a WEAK default the port # may override, so the main DEFINES both -- and nothing exported them. The # kernel-embedded runtime IMPORTS both (env.__hwjs_budget_uninitialized, # env.__hwjs_budget_not_refilled) and the loader binds a runtime import from # the MAIN's exports, so an unexported handler aborts the load the first time # the budget arm is reached: "rt import env. called before the main # provided it". Measured on a dynamic bash under the released HardwareJS # 0.1.0-dev.3 -- adding these surfaced both, 30 exports -> 32 (BRINTOS-2814). --export-if-defined=__hwjs_budget_uninitialized --export-if-defined=__hwjs_budget_not_refilled --export-if-defined=__hwjs_promise_i32 --export-if-defined=__wasm32_child_return # drive_abi=4 §4 host terminus surface (STATUS-CHANNEL-CONTRACT §4 last # paragraph, the HWJS_DRIVE_DONE_LIVE dispatch; §10 "export whitelists"). # EVERY image shape needs these two, static included — the host's DONE # recipient reads the channel word/payload and calls the hook when a chain # completes under the driver with a live outcome: # __hwjs_status_channel the per-thread channel BLOCK (data; defined # only in RT-carrying abi-4 images — if-defined # keeps abi<=3 images byte-identical). The RT ops # self-export via HWJS_RT_OP export_name; a DATA # symbol has no such attribute, hence this entry. # __hwjs_uncaught_unwinding the terminus hook. The RT's WEAK fallback # carries export_name, but when libc++abi's # STRONG definition wins the link the weak def's # export attribute is dropped with it — so a C++ # image (exactly the one that needs terminate # fidelity) lost the export without this entry. --export-if-defined=__hwjs_status_channel --export-if-defined=__hwjs_uncaught_unwinding # The signal trampoline, which the host calls at a breath: a loop that makes no # system call has no other delivery point. A dynamic main gets it from libc.so's # exports and a static one got nothing, so `kill -9` could not stop a static # compute loop (the host saw the signal pending at every breath and had no way # to run it). --export-if-defined=__wasm_signal_dispatch_pending --export-if-defined=__wasm32_signal_dispatch_restart # Fork stop-the-world handshake surface (PLAN-THREADS §3 I1(b), step 7: # fork under threads): the two process-wide DATA words the forking # thread's host servicer and every sibling thread's pump coordinate # through (Atomics over the shared linear memory). The per-thread ack and # mirror words are block fields (__hwjs_tcb_field). The companion ops # (__hwjs_fork_barrier_ok/_release, __hwjs_fork_child_collapse) # self-export via HWJS_RT_OP export_name. --export-if-defined=__hwjs_fork_stw --export-if-defined=__hwjs_fork_stw_seq ) CORO_EXPORTS_AUDITED=() # The WideSlot promise-reader family (__hwjs_promise_a), DERIVED from the merged closure by # the §3.5 owner audit rather than hand-listed beside its scalar siblings __hwjs_promise_i32/i64: # CoroutinizePass emits one reader per distinct ALIGNMENT a wide return uses, so the set is open and # a fixed list is a list that goes stale silently. Empty on every arm that does not run the audit, so # a static image stays byte-identical. CORO_EXPORTS_DERIVED=() # Set by the §3.5 force-export OWNER AUDIT when it actually ran (the libc.so-consumer arm and the # runtime-import arm). link_coro substitutes the audited list on exactly that condition — never on # "the array happens to be non-empty", which would silently ship an empty surface if the audit were # ever skipped. EXPORT_AUDIT_RAN=0 link_coro() { # DYNAMIC-MAIN (HWJS-5 STEP 2): source __indirect_function_table from env so a # dlopen'd PIC side module shares it (host-owned, like memory). Empty = the # default self-contained static image (the main defines+owns its own table). local dyn_table="" local -a dyn_exports=() if [[ "$DYNAMIC_MAIN" != "0" ]]; then dyn_table="--import-table" # DYNAMIC-MAIN .so->main runtime binding (HWJS-5 M2/M3): a dlopen'd PIC side # module imports the shared coro runtime + SjLj marker ABI + registrar ops # from env; the host wires the .so's env.* imports to the MAIN's exports (the # one instance owning the frame arena / parked slot / SjLj table). So the # main must EXPORT every op a .so may import. export-if-defined: each is # present only when some TU pulls it in (harmless no-op otherwise), so the # set is a superset of {answer,suspder,ljmod,forkmod,e8mod}.so's union. # frame arena + parked : __hwjs_frame_alloc/free/publish, set/clear_parked # promise/return-slot : __hwjs_promise_i32 (also listed below) # per-module registrars : __hwjs_register_suspends/_fpcast_adapter/_capsummary # SjLj marker ABI (M3-lj): hwjs_lj_arm_from + the record/match/select/value/ # clear/unwound family + hwjs_sj_record # flat xfer ops : __hwjs_xfer_descend/park/return/take # fork PARK LEAF (M3-fork): _Fork (+ fork wrapper) — bound to .so's env.fork # The registry CONSULTS (__hwjs_e8_refuse / capsummary lookup) are the MAIN's # IMPORTS the host sources from the kernel registry, not exports — omitted. # HWJS-5 M1 additions: # __stack_pointer : the process shadow-stack pointer GLOBAL (hard # --export, not if-defined: wasm-ld synthesizes it # for every non-relocatable link; legal because # +mutable-globals is in target_features). The # export is the mechanism by which the host hands # the process sp Global to a dlopen'd .so (a PIC # side module imports env.__stack_pointer). # __hwjs_ds_region_abi_v2: the DS-region version sentinel — a region-using # .so carries an UNDEFINED reference to it (the # never-silent v1/v2 pairing check); the host binds # it from the main's runtime. # __hwjs_promise_i64 : the i64 natural-return promise reader (the i32 # twin was already exported below); a .so whose # cascade reads an i64 promise imports it. # __hwjs_noreturn_completed: the F108 noreturn-breach witness — a .so with # a converted noreturn pump imports it. dyn_exports=( --export=__stack_pointer --export-if-defined=__hwjs_frame_alloc --export-if-defined=__hwjs_frame_free --export-if-defined=__hwjs_frame_publish --export-if-defined=__hwjs_set_parked --export-if-defined=__hwjs_clear_parked --export-if-defined=__hwjs_register_suspends --export-if-defined=__hwjs_register_fpcast_adapter --export-if-defined=__hwjs_register_capsummary --export-if-defined=__hwjs_ds_region_abi_v2 --export-if-defined=__hwjs_promise_i64 --export-if-defined=__hwjs_noreturn_completed --export-if-defined=hwjs_lj_arm_from --export-if-defined=hwjs_sj_record --export-if-defined=hwjs_lj_match --export-if-defined=hwjs_lj_selector --export-if-defined=hwjs_lj_value --export-if-defined=hwjs_lj_clear --export-if-defined=hwjs_lj_unwound --export-if-defined=__hwjs_xfer_descend --export-if-defined=__hwjs_xfer_park --export-if-defined=__hwjs_xfer_return --export-if-defined=__hwjs_xfer_take --export-if-defined=_Fork --export-if-defined=fork # drive_abi=4 status-channel surface (STATUS-CHANNEL-CONTRACT §10: # "New ops join DLOPEN_MAIN_OWNED_OPS and the export whitelists"). # export-if-defined: present only in RT-carrying images; today's abi≤3 # closures that lack them are byte-identical. All modules in a process # must address the MAIN's one channel block (§1) — these exports are # how a dlopen'd .so's env.__hwjs_status_* imports bind to it. --export-if-defined=__hwjs_status_channel --export-if-defined=__hwjs_status_park_exit --export-if-defined=__hwjs_status_baton --export-if-defined=__hwjs_status_clear --export-if-defined=__hwjs_status_adopt_top --export-if-defined=__hwjs_drive_adopt_parked --export-if-defined=__hwjs_status_raise_unwind --export-if-defined=__hwjs_status_raise_longjmp --export-if-defined=__hwjs_status_sj_register --export-if-defined=__hwjs_status_violation --export-if-defined=__hwjs_status_longjmp_lost # §4 terminus hook (2026-07-21, the uncaught-exit-0 fix): the EH # pre-lowering's process-exit-sink checks call it, so a check-emitting # .so (libc.so's own exit path) imports it; the main's definition — # libc++abi's strong std::terminate route in a C++ image, the RT's # loud weak fallback otherwise — must be the one every module binds. --export-if-defined=__hwjs_uncaught_unwinding ) # WASMLD_DYN_EXPORT_LIBC (HWJS-5 M1): space-separated symbol names a # fixture/distro wants surfaced from the MAIN for .so's to import (e.g. # "nanosleep read" so a side module's libc calls bind to the main's musl). # Each becomes --export-if-defined= (if-defined: the main only # exports what its closure actually carries — a misspelled name is then # visible as the .so's unresolved env import, the loud open-world path). # Loudly NOTEd so a widened export surface is always on the record. if [[ -n "${WASMLD_DYN_EXPORT_LIBC:-}" ]]; then echo "wasmld: NOTE (WASMLD_DYN_EXPORT_LIBC): exporting libc symbol(s) [${WASMLD_DYN_EXPORT_LIBC}] from the dynamic main for .so imports." >&2 for _dyn_sym in ${WASMLD_DYN_EXPORT_LIBC}; do dyn_exports+=( "--export-if-defined=${_dyn_sym}" ) done fi fi # BOOTSTRAP TLS export ABI (host pre-ctor __tls_base materialisation): # worker.mjs allocates a bootstrap TLS block in the per-image brk window and # calls __wasm_init_tls(block) BEFORE __wasm_call_ctors, so glibc ctors that # touch __thread state pre-main (malloc's `tcache`, a .tdata pointer reloc) # run against a real, materialised __tls_base instead of 0 (which smashes # heap metadata). __wasm32_get_tls_size/align size the block; __wasm_init_tls # is the lld-synthesized helper that sets __tls_base AND materialises the # .tdata template (memory.init + .tdata pointer relocs). __wasm_init_tls is # emitted only for a TLS image, so it is export-if-defined (a TLS-less image # would otherwise --export-error). A musl image built before this change does # NOT export these, so the worker's early-init is skipped for it and musl # takes its unchanged _start-time self-init path (no regression). local -a coro_exports=( "${CORO_EXPORT_SURFACE[@]}" ) if [[ "$EXPORT_AUDIT_RAN" == "1" ]]; then coro_exports=( "${CORO_EXPORTS_AUDITED[@]}" ) fi coro_exports+=( ${CORO_EXPORTS_DERIVED[@]+"${CORO_EXPORTS_DERIVED[@]}"} ) local _ip for _ip in ${LIBC_INTERPOSED_DATA[@]+"${LIBC_INTERPOSED_DATA[@]}"}; do coro_exports+=( "--export-if-defined=$_ip" ) done for _ip in ${LIBC_INTERPOSED_ALLOC[@]+"${LIBC_INTERPOSED_ALLOC[@]}"}; do coro_exports+=( "--export-if-defined=$_ip" ) done # --import-undefined arm only: re-derive the undefined-GLOBAL sanction from THESE inputs (see the # policy note at CORO_UNDEF_FLAG). Derived inside the link function, off the very argv about to be # linked, so the memory-auto-resize RE-link derives it again rather than reusing a stale set. local -a undef_flags=( "${CORO_UNDEF_FLAG[@]}" ) if [[ "$LIBC_IMPORT" == "1" ]] && derive_section_bounds "$WORK/section-bounds.o" "$@"; then set -- "$@" "$WORK/section-bounds.o" fi if [[ "$LIBC_IMPORT" != "1" ]]; then local _uga="$WORK/undef-globals.allow" derive_undef_global_allow "$_uga" "$@" undef_flags+=( "--allow-undefined-file=$_uga" ) echo "wasmld: NOTE (UNDEFINED-SYMBOL POLICY): ${CORO_UNDEF_FLAG[*]} (undefined DATA is a LINK ERROR, not an address-0 bind — UNLESS the RED knob is on, which says so above); undefined wasm GLOBALs sanctioned from the inputs' own symbol tables: [$(tr '\n' ' ' < "$_uga")]." >&2 fi "$WASM_LD" \ $dyn_table \ "${dyn_exports[@]}" \ --no-entry \ "${coro_exports[@]}" \ "${undef_flags[@]}" \ --error-limit=0 \ --import-memory=env,user_memory \ --shared-memory \ --initial-memory=$((INIT_PAGES * 65536)) \ --max-memory=$((MAX_PAGES * 65536)) \ -z stack-size=$STACK \ --gc-sections \ ${FINAL_CODE_FLAGS[@]+"${FINAL_CODE_FLAGS[@]}"} \ "$@" } # -shared SIDE-MODULE final link (HWJS-5 M1). Flag audit (each verified against # the pinned wasm-ld + the d1-dlopen fixture shapes): # --experimental-pic REQUIRED: -shared refuses to link without it. # -shared the point of the arm (PIC dylib: env.__memory_base/ # __table_base imports, __wasm_apply_data_relocs). # --no-entry a .so has no _start (harmless under -shared, explicit). # --import-table redundant under -shared PIC (the table import is # implied) but kept EXPLICIT: the shared # __indirect_function_table is the load-bearing dlsym # identity contract (ADR-0004), not an accident of PIC. # --shared-memory marks the env.memory import SHARED: the host memory # is the process SharedArrayBuffer, and a non-shared # memory import refuses to instantiate against it. # --no-check-features the merged.o's feature section need not match # wasm-ld's shared-memory expectations (atomics without # the full TLS feature set); feature policing here is # noise — the fixture recipe carries it for the same # reason. # --allow-undefined REQUIRED: the .so's libc/runtime refs are env imports # the host binds to the main's exports at dlopen. # --export-if-defined=__wasm_call_ctors the host loader's runCtors() # dispatch (the F117 registrars run through it; the # pinned brintos wasm-ld does NOT auto-export it). # --export-if-defined=__wasm_apply_data_relocs data-slot modules need the # loader to apply their PIC data relocations. # --Bsymbolic-non-weak[-functions] only when the link line asked for # -Bsymbolic or -Bsymbolic-functions (BSYMBOLIC_FLAG). # Caller-specified --export= flags arrive via LINK_FLAGS. link_shared() { "$WASM_LD" \ --experimental-pic \ -shared \ --no-entry \ --import-table \ --shared-memory \ --no-check-features \ --allow-undefined \ --export-if-defined=__wasm_call_ctors \ --export-if-defined=__wasm_apply_data_relocs \ ${BSYMBOLIC_FLAG:+"$BSYMBOLIC_FLAG"} \ ${FINAL_CODE_FLAGS[@]+"${FINAL_CODE_FLAGS[@]}"} \ "$@" } # final_link_head: the head of both final link lines, a program's and a side # module's, in FINAL_HEAD: merged.o, and the builtins object directly after it # where this link takes it. A name merged.o leaves to the object, on a line # without it, is an import nothing provides, and a side module has no audit of # its imports to catch that. Nothing drops the object after merged.o is read, # so the refusal is for a change that would. final_link_head() { FINAL_HEAD=( "$WORK/merged.o" ${HWJS_BUILTINS_OBJECT:+"$HWJS_BUILTINS_OBJECT"} ) [[ -z "$BUILTINS_OBJECT_UNRESOLVED" || -n "$HWJS_BUILTINS_OBJECT" ]] \ || fatal "merged.o leaves [$BUILTINS_OBJECT_UNRESOLVED] to the compiler-rt builtins object, and the final link line does not carry it." } # ── RELOCATION WIDTH AND DWARF AT THE FINAL LINK ──────────────────────────── # # wasm-ld writes every relocated immediate as a five-byte LEB, so that it can be # patched in place: a call's function index, a global.get of the stack pointer # or the status channel, the i32.const of a data or table address, a # call_indirect's type. A final link has nothing left to patch, and the padding # shipped: 10.6% of glibc bash, 9.3% of glibc libc.so's code, 7.8% of lua, read # off the shipped files by libexec/wasm-leb-width.mjs. The status-channel # lowering is call-dense (lua: 34,254 padded call immediates, 4,532 in its plain # build), so it paid the most. --compress-relocations writes each at its minimal # width. The instruction stream is the same function for function, and so are # the branch hints (the twin check below proves it on every DWARF link, and # test/final-link-leb-width.sh on a fresh one). # # wasm-ld refuses the flag while debug info is kept (lld/wasm/Driver.cpp, # checkOptions): the DWARF would address code offsets the compression moved. So # the flag rides with --strip-debug, and a link whose inputs carry DWARF decides # where it goes: # WASMLD_DWARF_SIDECAR_DIR= ship the image stripped and compressed, and # keep its DWARF in /.wasm: # the same link without the two flags, with its branch # hints written the same way. Its DWARF addresses that # twin's code, which decodes to the shipped image's # instructions function for function, so a shipped # (function, instruction) maps onto it. glibc's libc.so is # the case this exists for: its pool is built -O2 -g and # carried 10.3 MB of DWARF, 48.6% of the file, into every # guest that started a glibc program. # unset keep the DWARF in the image, as -g asked, and leave the # relocations padded, saying so. # A line that strips on its own (-s, -S, --strip-all, --strip-debug) asked for # the DWARF to go, so it is compressed and keeps no sidecar. # WASMLD_NO_COMPRESS_RELOCATIONS=1 leaves --compress-relocations out (the DWARF # decision is unchanged), for a before-and-after and the gate's RED arm. FINAL_CODE_FLAGS=() DWARF_TWIN=0 DWARF_TWIN_FILE="" final_code_policy() { # FINAL_CODE_FLAGS=(); DWARF_TWIN=0; DWARF_TWIN_FILE="" local _f _user_strips=0 _dwarf_in="" local -a _inputs=() for _f in ${LINK_FLAGS[@]+"${LINK_FLAGS[@]}"}; do case "$_f" in -s|-S|--strip-all|--strip-debug) _user_strips=1 ;; esac done # One start of the helper for all of the link's inputs. This asked # llvm-objdump --section-headers of each input in turn and a grep of each # answer: two processes an input on every link, the toolchain's own start # files and builtins archive among them, where a link otherwise asks LLVM # nothing its records answer (test/toolchain-link-facts.sh) and starts no # grep on a here-string (test/per-link-probes.sh case 12). In a guest a # process start is most of what a probe costs. if [[ $_user_strips == 0 ]]; then for _f in "$@"; do [[ -z "$_f" ]] || _inputs+=( "$_f" ); done _dwarf_in="$("$BRINT_TOOL" dwarf-inputs ${_inputs[@]+"${_inputs[@]}"} 2>&1)" \ || fatal "cannot read the final link's inputs to learn whether one carries DWARF (${_dwarf_in:0:300}). Which flags the final link takes depends on it. Refusing." fi if [[ -n "$_dwarf_in" && -z "${WASMLD_DWARF_SIDECAR_DIR:-}" ]]; then echo "wasmld: NOTE (final-link DWARF): '$_dwarf_in' carries DWARF and WASMLD_DWARF_SIDECAR_DIR is unset, so the image keeps it and its relocations stay padded (wasm-ld cannot write them at minimal width while DWARF is kept). Set WASMLD_DWARF_SIDECAR_DIR= to ship it stripped and keep the DWARF there." >&2 return 0 fi if [[ "${WASMLD_NO_COMPRESS_RELOCATIONS:-0}" == 1 ]]; then echo "wasmld: NOTE (WASMLD_NO_COMPRESS_RELOCATIONS=1): the final link leaves every relocated immediate five bytes wide." >&2 else FINAL_CODE_FLAGS+=( --compress-relocations ) fi FINAL_CODE_FLAGS+=( --strip-debug ) if [[ -n "$_dwarf_in" ]]; then command -v node >/dev/null 2>&1 \ || fatal "WASMLD_DWARF_SIDECAR_DIR: node is unavailable, and the DWARF twin is installed only after libexec/wasm-leb-width.mjs proves it describes the shipped image. Refusing rather than keeping DWARF nothing checked." DWARF_TWIN=1 # Under the output's own basename: wasm-ld writes it into the name section # as the module name, and the twin check requires that section identical. path_basename_v "$OUT" mkdir -p "$WORK/dwarf-twin" DWARF_TWIN_FILE="$WORK/dwarf-twin/$PATH_BASENAME" echo "wasmld: NOTE (final-link DWARF): '$_dwarf_in' carries DWARF: the image ships without it and the same link with it goes to WASMLD_DWARF_SIDECAR_DIR=$WASMLD_DWARF_SIDECAR_DIR." >&2 fi } # libc_pool_glob ARRAY DIR: append DIR/*.bc to ARRAY in C collation. Bash sorts # a glob by the caller's LC_COLLATE and the member pull is first-provider-wins, # so the pool order has to be a function of the member names alone: otherwise # the locale picks which of two twin members joins the link, and the same # inputs give two images. libc_pool_glob() { local LC_ALL=C local -n _lpg_out="$1" _lpg_out+=( "$2"/*.bc ) } fatal() { local m="$*" # A refusal names the output the caller asked for, not the staged copy. [[ -z "${BRINTLD_OUT_STAGE:-}" ]] || m="${m//"$OUT"/"$BRINTLD_OUT"}" echo "wasmld: FATAL (HWJS-3 coro arm): $m" >&2 exit 1 } # llvm_link_fatal : shows llvm-link's messages, at # most 60 lines of them, and refuses naming the cause only when those messages # show it. llvm_link_fatal() { local err="$1" what="$2" max=60 n=0 said="" cause="" pr="" local re="^Producer: '([^']*)' Reader: '([^']*)'" [[ -r "$err" ]] && n=$(wc -l <"$err") || true head -n "$max" -- "$err" >&2 2>/dev/null || true (( n <= max )) || echo "wasmld: ... $(( n - max )) more lines of llvm-link's output not shown" >&2 said="$(grep -m1 'error:' -- "$err" 2>/dev/null || true)" if grep -q 'symbol multiply defined' -- "$err" 2>/dev/null; then cause="a symbol is strongly defined by more than one input" # LLVM appends the producer and reader to every bitcode read error. elif pr="$(grep -o -m1 "Producer: '[^']*' Reader: '[^']*'" -- "$err" 2>/dev/null)" \ && [[ "${pr%%$'\n'*}" =~ $re && "${BASH_REMATCH[1]// /}" != "${BASH_REMATCH[2]// /}" ]]; then cause="an input's bitcode was written by another LLVM version" elif grep -q 'linked module is broken' -- "$err" 2>/dev/null; then cause="the merged module fails the IR verifier, on the lines above" fi said="${said//$'\r'/}" (( ${#said} <= 300 )) || said="${said:0:300}..." fatal "$what: ${cause:-the llvm-link output above does not show the cause}${said:+; llvm-link said: $said}." } # hwjs_checkout_unreadable : for a checkout whose git status was not # empty, refuses with "cannot read" when git status failed or a file it lists # as modified has no readable blob in HEAD; returns 1 otherwise, so the caller # refuses the checkout as DIRTY. hwjs_checkout_unreadable() { local d="$1" rc=0 out line said="" n=0 out="$(git -C "$d" status --porcelain 2>&1 >/dev/null)" || rc=$? if (( rc != 0 )); then while IFS= read -r line; do [[ "$line" =~ ^(error|fatal): ]] && { said="$line"; break; } done <<<"$out" (( ${#said} <= 300 )) || said="${said:0:300}..." said="git status exit $rc${said:+, $said}" else # A file whose blob git cannot read is listed as modified: git compares a # symlink by reading its blob, and an unreadable one never compares equal. # A submodule's commit is never in this store, and its line means DIRTY. out="$(git -C "$d" status --porcelain 2>/dev/null)" || true while IFS= read -r line && (( n < 20 )); do [[ "${line:0:1}" == [\ MT] && "${line:0:2}" == *[MT]* && "${line:3}" != \"* ]] || continue [[ "$(git -C "$d" ls-tree --full-tree HEAD -- "${line:3}" 2>/dev/null)" != 160000\ * ]] || continue n=$(( n + 1 )) git -C "$d" cat-file -e "HEAD:${line:3}" 2>/dev/null \ || { said="the blob HEAD records for ${line:3} cannot be read"; break; } done <<<"$out" [[ -n "$said" ]] || return 1 fi fatal "cannot read the checkout at $d: git could not tell whether it is clean${said:+ ($said)}, so the plugin's provenance cannot be checked. It is not reported as DIRTY: what git lists cannot be told apart from what it failed to read. An object store git cannot reach does this, such as an alternates path (.git/objects/info/alternates) that exists only on another host. Refusing." } # PASS LOG ANSWERS # What the pass plugins attested in their log, read once. Each gate was a grep, # and a process start is most of 100 ms in the guest; the log has a line per # coroutinized function, so the answers come from one awk and only the short # ones reach the shell. PASS_LOG_RE is the only spelling of each pattern: a # refusal's own grep takes it from here. The patterns stay in what gawk, mawk, # busybox awk and grep -E read alike: brackets, `.`, `*`, escapes of `[`. declare -A PASS_LOG_RE=( [coro_prov]='\[hwjs-coro\] PLUGIN-PROVENANCE' [eh_prov]='\[hwjs-eh-prelower\] PLUGIN-PROVENANCE' [rat_prov]='\[hwjs-retattr-truth\] PLUGIN-PROVENANCE' [spl_prov]='\[hwjs-split\] PLUGIN-PROVENANCE' [demit_prov]='\[hwjs-descemit\] PLUGIN-PROVENANCE' [nc_prov]='\[hwjs-nullcheck\] PLUGIN-PROVENANCE' [coro_summary]='\[hwjs-coro\] SUMMARY' [eh_clean]='\[hwjs-eh-prelower\] SUMMARY mode=on .*residual: invokes=0 landingpads=0 resumes=0 personalities=0 typeids=0' [rat_summary]='\[hwjs-retattr-truth\] SUMMARY fns=' [fd_summary]='\[hwjs-frame-defer\] SUMMARY fns=' [suspend]='SUSPEND-PUBLICATION .*protocol_forced=1' [parked]='PARKED-FLAG .*parked_flag_forced=1' [parked_abi]='PARKED-FLAG .*parked_abi=2' [drive]='DRIVE-CONTRACT' [drive2]='DRIVE-CONTRACT .*drive_abi=2' [drive3]='DRIVE-CONTRACT .*drive_abi=3' [drive4]='DRIVE-CONTRACT .*drive_abi=4' [sp_census]='SP-DELIVER-CENSUS' [sp_in_chain]='SP-DELIVER-CENSUS .*mode=in-chain' [sp_red]='SP-DELIVER-CENSUS .* red=' [zero_coro]='SUMMARY coroutinized=0 ' [channel]='CHANNEL-ADDRESSING' [budget]='BUDGET-KEYING' [budget_ok]='BUDGET-KEYING keying=instance-global budget_storage=wasm-global' [budget_lane]='BUDGET-KEYING .*budget_binding=lane-import' [effect]='\[hwjs-coro\] EFFECT-FACT-GUARD ' [effect_clean]='\[hwjs-coro\] EFFECT-FACT-GUARD .* refusals=0 ' [refuse]='REFUSE fn=' [alias_census]='unpublished_alias=[1-9]' [classify_only]='SUMMARY .*mode=classify-only' [tls]='TLS-CENSUS tls_globals=' [tls_zero]='TLS-CENSUS tls_globals=0 ' [abi]='ABI-MANIFEST section=hwjs.abi' [abi_tls]='ABI-MANIFEST section=hwjs.abi .*uses_tls=1' [preempt_census]='\[hwjs-coro\] PREEMPT-CENSUS ' ) # Not questions: what a refusal or a rare path prints. PASS_LOG_TLS_LINE='TLS-CENSUS' PASS_LOG_TLS_OR_ABI='TLS-CENSUS|ABI-MANIFEST' PASS_LOG_WAIVER='XMOD-UNWIND-WAIVER fn=' PASS_LOG_ALIAS_PAIR='UNPUBLISHED-SUSPENDER alias=[^ ]* aliasee=[^ ]*' PASS_LOG_PREEMPT_OPEN='\[hwjs-coro\] PREEMPT-OPEN ' PASS_LOG_COMPLETE='\[hwjs-descemit\] COMPLETENESS .*all_have_records=1' declare -A PASS_LOG_HIT=() PASS_LOG_MODES="" # # Fills PASS_LOG_HIT with each key's first line and PASS_LOG_MODES with the # channel modes, first seen first. Non-zero when the read did not finish: a # gate that wants a line to be absent must not take a failed read for a clean log. pass_log_read() { local log="$1" commit="$2" names="$3" k l table="" want n=0 local -A re=() for k in "${!PASS_LOG_RE[@]}"; do re[$k]="${PASS_LOG_RE[$k]}"; done [[ -z "$commit" ]] || { re[coro_stamp]="\\[hwjs-coro\\] PLUGIN-PROVENANCE commit=$commit dirty=0" re[eh_stamp]="\\[hwjs-eh-prelower\\] PLUGIN-PROVENANCE commit=$commit dirty=0" re[rat_stamp]="\\[hwjs-retattr-truth\\] PLUGIN-PROVENANCE commit=$commit dirty=0" re[spl_stamp]="\\[hwjs-split\\] PLUGIN-PROVENANCE commit=$commit dirty=0" re[demit_stamp]="\\[hwjs-descemit\\] PLUGIN-PROVENANCE commit=$commit dirty=0" re[nc_stamp]="\\[hwjs-nullcheck\\] PLUGIN-PROVENANCE commit=$commit dirty=0" } for k in "${!re[@]}"; do table+="$k"$'\t'"${re[$k]}"$'\n'; n=$((n + 1)); done PASS_LOG_HIT=(); PASS_LOG_MODES="" : > "$names" || return 1 [[ -f "$log" ]] || return 1 # The program and the table go in files: in the guest an argv and environment # over 8 KiB stop the machine, and configure's environment is most of that. printf '%s' "$table" > "$names.table" || return 1 printf '%s' ' function lift(pat, skip, s) { s = $0 while (match(s, pat)) { print substr(s, RSTART + skip, RLENGTH - skip) > names s = substr(s, RSTART + RLENGTH) } } BEGIN { names = ENVIRON["PASS_LOG_NAMES"] table = names ".table" while ((getline line < table) > 0) { t = index(line, "\t") if (!t) continue n++ key[n] = substr(line, 1, t - 1) pat[n] = substr(line, t + 1) if (n > 1) any = any "|" any = any "(" pat[n] ")" } } $0 ~ any { for (i = 1; i <= n; i++) if (!(key[i] in seen) && $0 ~ pat[i]) { seen[key[i]] = 1; print key[i] "\t" $0 } } /COROUTINIZE fn=/ { lift("COROUTINIZE fn=[^ ]*", 15) } /UNPUBLISHED-SUSPENDER alias=/ { lift("UNPUBLISHED-SUSPENDER alias=[^ ]*", 28) } /CHANNEL-ADDRESSING pass=/ { s = $0 while (match(s, "CHANNEL-ADDRESSING pass=[a-z-]* mode=[a-z-]*")) { m = substr(s, RSTART, RLENGTH) s = substr(s, RSTART + RLENGTH) sub(/.* /, "", m) if (!(m in mode)) { mode[m] = 1; print "\t" m } } } END { print "\tend " n } ' > "$names.awk" || return 1 PASS_LOG_NAMES="$names" LC_ALL=C awk -f "$names.awk" "$log" > "$names.answers" || return 1 want="" while IFS= read -r l; do k="${l%%$'\t'*}" if [[ -n "$k" ]]; then PASS_LOG_HIT[$k]="${l#*$'\t'}" elif [[ "$l" == $'\tend '* ]]; then want="${l#$'\t'end }" else PASS_LOG_MODES+="${PASS_LOG_MODES:+$'\n'}${l#$'\t'}" fi done < "$names.answers" [[ "$want" == "$n" ]] } pass_log_has() { [[ -n "${PASS_LOG_HIT[$1]+x}" ]]; } # End of the pass log answers. # PER-LINK PROBES # # Questions the driver asks in every link. In the guest a fork costs 50 ms # before the child runs and an exec 40 ms more, so file_kind_v, export_owner_v # and the three below them start no process, and roots_main_scan starts one # llvm-nm whatever the number of roots. file_kind_v() { # bc | wasm | archive | thin | other in $FILE_KIND (by magic; extensions lie # under autotools). # `read -d ''` ends a field at a NUL and cannot hold one, so the first field # is the leading bytes up to the first NUL, and a wasm module's "\0asm" is an # empty first field followed by "asm". An unreadable path is `other`. local _fk_a='' _fk_b='' FILE_KIND=other { IFS= read -r -d '' -n 8 _fk_a; IFS= read -r -d '' -n 3 _fk_b; } 2>/dev/null < "$1" || true case "$_fk_a" in BC$'\xc0\xde'*) FILE_KIND=bc ;; '!'$'\n') FILE_KIND=archive ;; '!'$'\n') FILE_KIND=thin ;; # an ar archive of path references '') if [[ "$_fk_b" == asm ]]; then FILE_KIND=wasm; fi ;; esac } file_kind() { # The same answer on stdout, for a caller inside $(...); that costs a fork. file_kind_v "$1" echo "$FILE_KIND" } roots_main_scan() { # ...: do the roots define `main`, and `__main_argc_argv`? Answers in # $roots_have_main and $roots_have_argcargv. One llvm-nm for all the roots, # through the response file, kept in $ROOTS_LISTING for builtins_object_roots. # A line whose last field is the name answers, as awk's $NF == name did; the # header of a several-file listing ends in ':' and is neither name. local _rms _rms_re roots_have_main=0; roots_have_argcargv=0 ROOTS_LISTED=(); ROOTS_LISTING="" [[ $# -gt 0 ]] || return 0 ROOTS_LISTING="$(run_llvm_bulk hwjs_nm --defined-only "$@" 2>/dev/null)" ROOTS_LISTED=( "$@" ) _rms=$'\n'"$ROOTS_LISTING"$'\n' _rms_re=$'[ \t\n]main[ \t]*\n' if [[ $_rms =~ $_rms_re ]]; then roots_have_main=1; fi _rms_re=$'[ \t\n]__main_argc_argv[ \t]*\n' if [[ $_rms =~ $_rms_re ]]; then roots_have_argcargv=1; fi } # roots_listed_v ...: ROOTS_LISTED_SAME=1 when they are the roots # roots_main_scan listed, or those and the main bridge after them, which # defines main and nothing else. ROOTS_LISTED=(); ROOTS_LISTING="" roots_listed_v() { local -a _rl=( "$@" ) local _rl_i ROOTS_LISTED_SAME=0 [[ ${#ROOTS_LISTED[@]} -gt 0 ]] || return 0 if (( ${#_rl[@]} == ${#ROOTS_LISTED[@]} + 1 )) && [[ "${_rl[${#_rl[@]}-1]}" == "${WORK:-}/main_bridge.bc" ]]; then unset "_rl[${#_rl[@]}-1]" fi (( ${#_rl[@]} == ${#ROOTS_LISTED[@]} )) || return 0 for _rl_i in "${!ROOTS_LISTED[@]}"; do [[ "${_rl[$_rl_i]}" == "${ROOTS_LISTED[$_rl_i]}" ]] || return 0 done ROOTS_LISTED_SAME=1 } # The force-export owner of a name. export_owner_tables # ... turns the audit's two lists into lookup tables for # the names given: a line is a key, behind a ':' so that an empty line is one # too, and it is kept only if one of the names could look it up. The tables # then hold the names' lines whatever the main defines, and the audit gives 28 # names: bash before 5.1 never grows an associative array's 128 buckets, and a # table of every line cost there the square of their number. One awk finds the # lines: libc.so exports thousands of names, and a turn of a bash loop is most # of a millisecond in the guest. It returns 1 when the awk fails. # export_owner_v answers in $EXPORT_OWNER: main | both | libc.so | rt, or # empty when no side owns the name; for a name the tables were not built for # it says so and returns 1. A name is compared as text, not read as a pattern. declare -A EXPORT_OWNER_ASKED=() EXPORT_OWNER_MAIN_DEFS=() EXPORT_OWNER_LIBC_EXPORTS=() # Linker-synthesized symbols wasm-ld itself defines on a main link (owner=main by construction). EXPORT_OWNER_SYNTH=" __heap_base __data_end __wasm_call_ctors __wasm_init_tls __stack_pointer __tls_base " export_owner_tables() { local _eo_line _eo_sym _eo_names="" _eo_hits local -a _eo_lines EXPORT_OWNER_ASKED=(); EXPORT_OWNER_MAIN_DEFS=(); EXPORT_OWNER_LIBC_EXPORTS=() for _eo_sym in "${@:3}"; do EXPORT_OWNER_ASKED[":$_eo_sym"]=1 # a name with a newline in it is no line of either list [[ "$_eo_sym" == *$'\n'* ]] || _eo_names+=":$_eo_sym"$'\n' done [[ -n "$_eo_names" ]] || return 0 mapfile -t _eo_lines <<<"$1" _eo_hits="$(EO_NAMES="$_eo_names" EO_NDEFS="${#_eo_lines[@]}" LC_ALL=C awk ' BEGIN { n = split(ENVIRON["EO_NAMES"], a, "\n") for (i = 1; i <= n; i++) if (a[i] != "") { s = substr(a[i], 2); def[s] = 1; libc["function " s] = 1; libc["global " s] = 1 } nd = ENVIRON["EO_NDEFS"] + 0 } NR <= nd { if ($0 in def) print "D" $0; next } $0 in libc { print "L" $0 }' <<<"$1"$'\n'"$2")" || return 1 _eo_lines=() [[ -z "$_eo_hits" ]] || mapfile -t _eo_lines <<<"$_eo_hits" for _eo_line in ${_eo_lines[@]+"${_eo_lines[@]}"}; do case "$_eo_line" in D*) EXPORT_OWNER_MAIN_DEFS[":${_eo_line#D}"]=1 ;; L*) EXPORT_OWNER_LIBC_EXPORTS[":${_eo_line#L}"]=1 ;; esac done } export_owner_v() { local _eo_def=":$1" _eo_fn=":function $1" _eo_gl=":global $1" _eo_libc=0 EXPORT_OWNER="" if [[ -z "${EXPORT_OWNER_ASKED[$_eo_def]+x}" ]]; then echo "wasmld: export_owner_v: '$1' is not one of the names export_owner_tables was given, and the tables hold an answer for those names only" >&2 return 1 fi if [[ -n "${EXPORT_OWNER_LIBC_EXPORTS[$_eo_fn]+x}" || -n "${EXPORT_OWNER_LIBC_EXPORTS[$_eo_gl]+x}" ]]; then _eo_libc=1 fi if [[ -n "${EXPORT_OWNER_MAIN_DEFS[$_eo_def]+x}" || "$EXPORT_OWNER_SYNTH" == *" $1 "* ]]; then EXPORT_OWNER=main if [[ $_eo_libc == 1 ]]; then EXPORT_OWNER=both; fi elif [[ $_eo_libc == 1 ]]; then EXPORT_OWNER=libc.so elif [[ "${WASMLD_RT_IMPORT:-0}" == "1" && ( "$1" == __hwjs_* || "$1" == hwjs_* ) ]]; then EXPORT_OWNER=rt fi } # Questions about a value the shell already holds. # # read_file_v FILE answers in $READ_FILE what "$(cat FILE 2>/dev/null)" holds: # the bytes with any NUL dropped and the trailing newlines stripped, empty when # the file cannot be read. bash's own substitution would also say on stderr # that it dropped a NUL; this does not. read_file_v() { local -a _rf_parts=() local IFS= READ_FILE="" { mapfile -t -d '' _rf_parts < "$1"; } 2>/dev/null || return 0 READ_FILE="${_rf_parts[*]-}" READ_FILE="${READ_FILE%"${READ_FILE##*[!$'\n']}"}" } # line_in_v VAR LINE: is LINE one of the lines of the text in variable VAR, # compared as text? LINE_IN=1 or 0, which is grep -qxF -- LINE <<<"$VAR" for a # LINE with no newline. The text is passed by name: a copy of a large listing # into an argument costs as much as the grep. Past PROBE_TEXT_MAX characters the # shell's scan costs more than the grep, so the grep answers; whether the text is # past it is read off the one character there, since even ${#VAR} copies it. PROBE_TEXT_MAX=131072 line_in_v() { local -n _li_ref="$1" LINE_IN=0 if [[ -n "${_li_ref:PROBE_TEXT_MAX:1}" ]]; then if grep -qxF -- "$2" <<<"$_li_ref"; then LINE_IN=1; fi elif [[ $'\n'"$_li_ref"$'\n' =~ $'\n'"$2"$'\n' ]]; then LINE_IN=1 fi } # nm_line_v VAR KINDS NAME: does a line of the llvm-nm listing in variable VAR # end in white space, one of the kind letters of the bracket KINDS, a space and # NAME, NAME read as text? NM_LINE=1 or 0, which is # grep -qE "[[:space:]]KINDS NAME$" <<<"$VAR" for a NAME of letters, digits and # _. In the shell the listing is one string with a newline either side, so the # white space before the kind could be the newline that ends the line before: # that is a line that starts with the kind, which llvm-nm never prints, and then # grep decides, as it does past PROBE_TEXT_MAX characters. nm_line_v() { local -n _nl_ref="$1" local _nl_s NM_LINE=0 if [[ -z "${_nl_ref:PROBE_TEXT_MAX:1}" ]]; then _nl_s=$'\n'"$_nl_ref"$'\n' [[ $_nl_s =~ [[:space:]]$2" $3"$'\n' ]] || return 0 if [[ ! $_nl_s =~ $'\n'$2" $3"$'\n' ]]; then NM_LINE=1; return 0; fi fi ere_text_v "$3" if grep -qE "[[:space:]]$2 $ERE_TEXT\$" <<<"$_nl_ref"; then NM_LINE=1; fi } # nm_part_v VAR defined|undefined: the lines of the llvm-nm listing of one file # in variable VAR that the same llvm-nm run with --defined-only, or with # --undefined-only, prints, in $NM_PART. llvm-nm picks both by the symbol's # undefined flag, and it is the flag that leaves a line's address column blank # (U, w, v), so an undefined symbol's line is one that starts with a space. # A listing of several files is not one this reads. nm_part_v() { local -n _np_ref="$1" case "$2" in defined) NM_PART="$(awk '!/^ /' <<<"$_np_ref")" ;; undefined) NM_PART="$(awk '/^ /' <<<"$_np_ref")" ;; *) fatal "nm_part_v: '$2' is neither defined nor undefined" ;; esac } # nm_llvm_import_v VAR: is the last field of an undefined line of the llvm-nm # listing of one file in variable VAR a name that starts with llvm.? # NM_LLVM_IMPORT=1 or 0: whether nm_part_v VAR undefined, awk '{print $NF}' and # grep '^llvm\.' would print anything, asked with one match on the whole text. nm_llvm_import_v() { local -n _nli_ref="$1" local _nli_re=$'\n ([^\n]*[ \t])?llvm\\.[^ \t\n]*[ \t]*\n' NM_LLVM_IMPORT=0 if [[ $'\n'"$_nli_ref"$'\n' =~ $_nli_re ]]; then NM_LLVM_IMPORT=1; fi } # sorted_v ARRAY WORD...: the words in byte order (LC_ALL=C sort's), in ARRAY. # For the few keys of an associative array, whose own order follows a hash of # the key and so moves with a path that holds the link's random directory. sorted_v() { local -n _sv_out="$1"; shift local LC_ALL=C _sv_w _sv_i _sv_out=() for _sv_w in "$@"; do _sv_i=${#_sv_out[@]} while (( _sv_i > 0 )) && [[ "${_sv_out[_sv_i - 1]}" > "$_sv_w" ]]; do _sv_out[_sv_i]="${_sv_out[_sv_i - 1]}"; _sv_i=$(( _sv_i - 1 )) done _sv_out[_sv_i]="$_sv_w" done } # ere_text_v TEXT: TEXT as an extended regular expression that matches it and # nothing else, in $ERE_TEXT. ere_text_v() { local _et_c _et_i ERE_TEXT="" for (( _et_i = 0; _et_i < ${#1}; _et_i++ )); do _et_c="${1:_et_i:1}" case "$_et_c" in '^') ERE_TEXT+='\^' ;; ']') ERE_TEXT+='[]]' ;; '\') ERE_TEXT+='[\]' ;; [.\[\{\}\(\)*+?\$\|]) ERE_TEXT+="[$_et_c]" ;; *) ERE_TEXT+="$_et_c" ;; esac done } # ar_names_repeat_v TABLE: is a line of an llvm-ar t TABLE in it twice? # AR_REPEAT=1 or 0. Where it says 0, sort | uniq -d of the table prints nothing. ar_names_repeat_v() { local _ar_m local -a _ar_lines=() local -A _ar_seen=() AR_REPEAT=0 mapfile -t _ar_lines <<<"$1" for _ar_m in ${_ar_lines[@]+"${_ar_lines[@]}"}; do if [[ -n "${_ar_seen[":$_ar_m"]+x}" ]]; then AR_REPEAT=1; return 0; fi _ar_seen[":$_ar_m"]=1 done } # End of the per-link probes. # THE BUILTINS OBJECT # # compiler-rt's helpers reach a program link or a side module in one of two # ways. The bitcode TU (builtins-wasm32-pic.bc) rides in the merged module: the # link compiles all of it and the final link drops what the module does not # call. Or the sysroot # holds that TU compiled once, builtins-wasm32-pic.o beside it # (sysroot/builtins-object.sh), and the final link resolves the helpers out of # it as out of any object. Then no link compiles them, and a helper the program # needs and the object lacks is an undefined symbol at the final link, which is # what it is with the TU. # # The object stands in for the TU on its stamp's word alone, .stamp, # written by the script from the run that compiled it: # brintium-builtins-object 2 # tu sha256=<64 hex> # object sha256=<64 hex> # pass commit=<40 hex> dirty=<0|1> # census defined= exempt_native= open_fns=0 coroutinized=0 # forms
... # names ... # The pass line is the plugin's own attestation in that run and the census is # its own count: every function it met in the TU is native to it and none # became a coroutine. That is what lets the object skip the two scans a # native-stage input gets, the one for calls into coroutines and the one for # loops: the pass has seen these functions, and at the commit this link's # plugins are held to. A link that holds its plugins to no commit has nothing # to hold the object to, and compiles the TU. # # The forms are the merged compiles the script found to give these functions # the same code as the object: "side", a side module's, and "side-abi4-lanes", # a side module's under the status channel with lane addressing, each with and # without what the form's name leaves out (the EH pre-lowering, frame # deferral). A side module takes the object only from a stamp that names its # own form. "main" is a program's, and stands for every program link: what the # script compares there is the compile with no form knob set, and with none of # the pass. Version 1 had no forms line and serves a program link alone. # # builtins_object_stamp reads the stamp and # answers in $BUILTINS_OBJECT_WHY: empty when the object can be linked, else # why not. The forms go to $BUILTINS_OBJECT_FORMS, space-separated. The last # thing it does is hash the TU and the object and hold them # to the stamp's two digests, in one sha256sum: a TU rebuilt beside an older # pair is then seen by every link, not only by the make rule. The names go to # BUILTINS_OBJECT_NAMES, keyed ":name". builtins_object_defs prints them as # strong definitions for the archive pull's list. # # A PROGRAM'S OWN DEFINITION. builtins_object_roots ... says which of the # names the roots define globally, weak ones too, in $BUILTINS_OBJECT_OWN. The # TU's copy of such a name is made internal and the program's is linked; an # object's cannot be, so that link compiles the TU, on the path it always took. # # THE MODULE MUST DEFINE NONE OF THE NAMES, UNDER ANY LINKAGE. The backend calls # a helper by name, and inside one object a name is one symbol: a function of # the merged module called __udivti3 takes every such call, a static one too, # and the final link sees nothing undefined. With the TU in the module its # external definition held the bare name and llvm-link renamed a local one. So # once the module is whole, builtins_object_own says # which of the names it defines: all of them in $BUILTINS_OBJECT_OWN, the # strong external ones in $BUILTINS_OBJECT_OWN_STRONG. If there is one the TU # joins after all. What is left to find by then is a static function, an # archive member's copy demoted to a local, and a member's weak copy: the TU's # definition takes the name from each, as it did as a root. declare -A BUILTINS_OBJECT_NAMES=() BUILTINS_OBJECT_WHY=""; BUILTINS_OBJECT_OWN=""; BUILTINS_OBJECT_OWN_STRONG=""; BUILTINS_OBJECT_FORMS="" builtins_object_stamp() { local _bo_obj="$1" _bo_tu="$2" _bo_expect="$3" _bo_key _bo_rest _bo_name local _bo_head="" _bo_pass="" _bo_census="" _bo_names="" _bo_tu_sha="" _bo_obj_sha="" _bo_have _bo_forms="" local -a _bo_list=() BUILTINS_OBJECT_NAMES=(); BUILTINS_OBJECT_WHY=""; BUILTINS_OBJECT_FORMS="" if [[ ! -f "$_bo_obj" ]]; then BUILTINS_OBJECT_WHY="there is no $_bo_obj (make -C sysroot builtins-pic)"; return 0 fi if [[ ! -f "$_bo_obj.stamp" || ! -r "$_bo_obj.stamp" ]]; then BUILTINS_OBJECT_WHY="$_bo_obj has no readable stamp beside it, so nothing says what it was compiled from"; return 0 fi while IFS=' ' read -r _bo_key _bo_rest || [[ -n "$_bo_key" ]]; do case "$_bo_key" in brintium-builtins-object) _bo_head="$_bo_rest" ;; tu) _bo_tu_sha="$_bo_rest" ;; object) _bo_obj_sha="$_bo_rest" ;; pass) _bo_pass="$_bo_rest" ;; census) _bo_census="$_bo_rest" ;; forms) _bo_forms="$_bo_rest" ;; names) _bo_names="$_bo_rest" ;; esac done < "$_bo_obj.stamp" if [[ "$_bo_head" != 1 && "$_bo_head" != 2 ]]; then BUILTINS_OBJECT_WHY="$_bo_obj.stamp is not a version 1 or 2 record"; return 0 fi if [[ "$_bo_head" == 2 && ! "$_bo_forms" =~ ^[a-z0-9-]+(\ [a-z0-9-]+)*$ ]]; then BUILTINS_OBJECT_WHY="$_bo_obj.stamp is a version 2 record with no forms line it can be read by (forms [$_bo_forms])"; return 0 fi if [[ ! "$_bo_pass" =~ ^commit=([0-9a-f]{40})\ dirty=([01])$ ]]; then BUILTINS_OBJECT_WHY="$_bo_obj.stamp names no pass run (pass [$_bo_pass])"; return 0 fi if [[ "${BASH_REMATCH[2]}" != 0 ]]; then BUILTINS_OBJECT_WHY="it went through plugins built from a dirty tree"; return 0 fi if [[ -z "$_bo_expect" ]]; then BUILTINS_OBJECT_WHY="this link holds its plugins to no commit, so there is none to hold the object to"; return 0 fi if [[ "${BASH_REMATCH[1]}" != "$_bo_expect" ]]; then BUILTINS_OBJECT_WHY="it went through the pass at commit ${BASH_REMATCH[1]} and this link's plugins are held to $_bo_expect"; return 0 fi if [[ ! "$_bo_census" =~ ^defined=([1-9][0-9]*)\ exempt_native=([1-9][0-9]*)\ open_fns=0\ coroutinized=0$ \ || "${BASH_REMATCH[1]}" != "${BASH_REMATCH[2]}" ]]; then BUILTINS_OBJECT_WHY="$_bo_obj.stamp does not record every function as native to the pass (census [$_bo_census])"; return 0 fi read -r -a _bo_list <<<"$_bo_names" for _bo_name in ${_bo_list[@]+"${_bo_list[@]}"}; do if [[ ! "$_bo_name" =~ ^[A-Za-z_][A-Za-z0-9_.\$]*$ ]]; then BUILTINS_OBJECT_NAMES=() BUILTINS_OBJECT_WHY="$_bo_obj.stamp lists [$_bo_name], which is not a symbol name"; return 0 fi BUILTINS_OBJECT_NAMES[":$_bo_name"]=1 done if [[ ${#BUILTINS_OBJECT_NAMES[@]} == 0 ]]; then BUILTINS_OBJECT_WHY="$_bo_obj.stamp lists no names"; return 0 fi if [[ ! "$_bo_tu_sha" =~ ^sha256=[0-9a-f]{64}$ || ! "$_bo_obj_sha" =~ ^sha256=[0-9a-f]{64}$ ]]; then BUILTINS_OBJECT_NAMES=() BUILTINS_OBJECT_WHY="$_bo_obj.stamp carries no digest of the TU or of the object"; return 0 fi if [[ -n "${LINK_FACTS_SHA[$_bo_tu]:-}" && -n "${LINK_FACTS_SHA[$_bo_obj]:-}" ]]; then _bo_have="${LINK_FACTS_SHA[$_bo_tu]} ${LINK_FACTS_SHA[$_bo_obj]}" else _bo_have="$(sha256sum "$_bo_tu" "$_bo_obj" 2>/dev/null | cut -c1-64 | paste -sd' ' - || true)" fi if [[ "$_bo_have" != "${_bo_tu_sha#sha256=} ${_bo_obj_sha#sha256=}" ]]; then BUILTINS_OBJECT_NAMES=() BUILTINS_OBJECT_WHY="$_bo_obj.stamp was written for another TU or another object than the two beside it (make -C sysroot builtins-pic)"; return 0 fi if [[ "$_bo_head" == 1 ]]; then BUILTINS_OBJECT_FORMS="main"; else BUILTINS_OBJECT_FORMS="$_bo_forms"; fi } # builtins_object_form : whether the stamp just read names ; if it # does not, $BUILTINS_OBJECT_WHY says so and the names are dropped. builtins_object_form() { [[ " $BUILTINS_OBJECT_FORMS " == *" $1 "* ]] && return 0 BUILTINS_OBJECT_NAMES=() BUILTINS_OBJECT_WHY="its stamp records the forms [$BUILTINS_OBJECT_FORMS] and not $1, the one this link compiles in" } builtins_object_roots() { local _bo_key _bo_names="" _bo_listing BUILTINS_OBJECT_OWN="" [[ $# -gt 0 ]] || return 0 for _bo_key in "${!BUILTINS_OBJECT_NAMES[@]}"; do _bo_names+=" ${_bo_key#:}"; done # A listing that fails is an empty one here, as it was for the TU's own # scan: a root llvm-nm cannot read stops the merge just below. roots_listed_v "$@" if [[ $ROOTS_LISTED_SAME == 1 ]]; then _bo_listing="$ROOTS_LISTING" else _bo_listing="$( { run_llvm_bulk hwjs_nm --defined-only "$@" 2>/dev/null || true; } )" fi BUILTINS_OBJECT_OWN="$(LC_ALL=C awk -v names="$_bo_names" ' BEGIN { n = split(names, a, " "); for (i = 1; i <= n; i++) want[a[i]] = 1 } NF >= 2 && $(NF-1) ~ /^[A-Z]$/ && ($NF in want) && !seen[$NF]++ { own = own (own == "" ? "" : " ") $NF } END { print own }' <<<"$_bo_listing")" } builtins_object_own() { local _bo_key _bo_names="" _bo_out BUILTINS_OBJECT_OWN=""; BUILTINS_OBJECT_OWN_STRONG="" for _bo_key in "${!BUILTINS_OBJECT_NAMES[@]}"; do _bo_names+=" ${_bo_key#:}"; done # A definition is any kind but U and w; a strong external one is upper case # and not W or V. _bo_out="$(LC_ALL=C awk -v names="$_bo_names" ' BEGIN { n = split(names, a, " "); for (i = 1; i <= n; i++) want[a[i]] = 1 } NF >= 2 && ($NF in want) && $(NF-1) ~ /^[A-Za-z]$/ && $(NF-1) != "U" && $(NF-1) != "w" { if (!any[$NF]++) own = own (own == "" ? "" : " ") $NF if ($(NF-1) ~ /^[A-Z]$/ && $(NF-1) != "W" && $(NF-1) != "V" && !st[$NF]++) strong = strong (strong == "" ? "" : " ") $NF } END { print own "|" strong }' <<<"$1")" BUILTINS_OBJECT_OWN="${_bo_out%%|*}" BUILTINS_OBJECT_OWN_STRONG="${_bo_out#*|}" } builtins_object_defs() { local _bo_key for _bo_key in "${!BUILTINS_OBJECT_NAMES[@]}"; do printf 'T %s\n' "${_bo_key#:}"; done } # The archive an extraction directory under $WORK was unpacked from, so a pool # member can be named the way a native linker names it: archive(member). declare -A POOL_AR_OF=() pool_input_label() { local _pl_dir="${1%/*}" if [[ "$1" == */* && -n "$_pl_dir" && -n "${POOL_AR_OF[$_pl_dir]:-}" ]]; then printf '%s(%s)' "${POOL_AR_OF[$_pl_dir]}" "${1##*/}" else printf '%s' "$1" fi } # strong_def_kind : the llvm-nm kind of 's strong global # definition in the nm listing on stdin, or nothing. It reads the whole # listing: an early exit would end the nm feeding it with SIGPIPE. strong_def_kind() { awk -v s="$1" '!k && NF >= 2 && $NF == s && $(NF-1) ~ /^[A-Z]$/ && $(NF-1) != "W" && $(NF-1) != "V" && $(NF-1) != "U" { k = $(NF-1) } END { if (k) print k }' } # def_kind_class : sets DEF_KIND_CLASS to "function", "data # object", or empty for a kind that is neither. def_kind_class() { case "$1" in T) DEF_KIND_CLASS=function ;; D|B|R|C|S|G) DEF_KIND_CLASS="data object" ;; *) DEF_KIND_CLASS="" ;; esac } # pool_demotion_kind_check