#!/bin/sh # SPDX-License-Identifier: GPL-2.0-or-later # Copyright (C) 2026 Tsiry Sandratraina # # Build the FreeBSD kernel for wasm (.agents/freebsd.md): the FreeBSD source # tree (sparse) with kernel/patches/freebsd/ applied, FreeBSD's config(8) # built for the host, the GENERIC kernel as a wasm64 module with kwemu # linked in, and a root file system from FreeBSD/arm64's rescue set. # # kernel/freebsd.sh src clone FreeBSD (sparse) into vendor/src/freebsd, apply the patches # kernel/freebsd.sh tools build config(8) into vendor/build/freebsd-tools # kernel/freebsd.sh kernel zig build (kwemu), config + build GENERIC and GENERIC_MP # (wasm64), lowered to vendor/build/freebsd/freebsd32.wasm # and freebsd-mp32.wasm # kernel/freebsd.sh rootfs vendor/build/freebsd/root.fs: UFS image of the arm64 rescue set # kernel/freebsd.sh image vendor/build/freebsd/freebsd.img: UFS disk of the base set # kernel/freebsd.sh all src, tools, kernel, rootfs, image # kernel/freebsd.sh run [ARGS] boot single-user from root.fs on the SDK host # kernel/freebsd.sh boot [ARGS] boot multi-user from freebsd.img (--disk) to a login prompt # CPUS=N kernel/freebsd.sh boot|run the same on N CPUs (GENERIC_MP, --cpus N) # MEM=N kernel/freebsd.sh boot memory in MiB (default 1024: pkg's catalogue # processing is killed at 256; run keeps 256) # kernel/freebsd.sh export re-export kernel/patches/freebsd from branch kw-wasm # # Needs clang and lld 22 from Homebrew (LLVM_BIN, WASM_LD override them), # bmake, yacc and lex, Zig 0.16, Node 24 with JSPI (--experimental-wasm-jspi), # and, for rootfs, NetBSD's makefs (kernel/netbsd.sh src tools builds it). set -e root=$(cd "$(dirname "$0")/.." && pwd) src=$root/vendor/src/freebsd tools=$root/vendor/build/freebsd-tools out=$root/vendor/build/freebsd compile=$src/sys/wasm/compile/GENERIC compile_mp=$src/sys/wasm/compile/GENERIC_MP CPUS=${CPUS:-1} FREEBSD_REPO=${FREEBSD_REPO:-https://github.com/freebsd/freebsd-src} FREEBSD_COMMIT=${FREEBSD_COMMIT:-44de1df2a033} # main, 2026-11-28 LLVM_BIN=${LLVM_BIN:-/opt/homebrew/opt/llvm/bin} WASM_LD=${WASM_LD:-/opt/homebrew/bin/wasm-ld} WASM_OPT=${WASM_OPT:-wasm-opt} # Binaryen >= 133 (--table64-lowering) BMAKE=${BMAKE:-bmake} MAKEFS=${MAKEFS:-$root/vendor/build/netbsd-tools/bin/nbmakefs} # The root file system: FreeBSD 15.1/arm64's base set, of which root.fs # takes /rescue (one static binary under 147 names, sh and init among them). BASE_URL=${BASE_URL:-https://download.freebsd.org/releases/arm64/aarch64/15.1-RELEASE/base.txz} BASE_SHA256=5b7a46a0abfbe23a1d4454b5600e2efcfce16b705bc7e9c851c37470c035ef98 # What the kernel and config(8) need from the tree. sparse="sys share/mk usr.sbin/config" do_src() { if [ ! -d "$src/.git" ]; then mkdir -p "$root/vendor/src" git clone --filter=blob:none --no-checkout "$FREEBSD_REPO" "$src" git -C "$src" sparse-checkout init --cone # shellcheck disable=SC2086 git -C "$src" sparse-checkout set $sparse git -C "$src" checkout -q "$FREEBSD_COMMIT" fi if ! git -C "$src" rev-parse -q --verify kw-wasm >/dev/null; then git -C "$src" checkout -q -b kw-wasm "$FREEBSD_COMMIT" git -C "$src" am "$root"/kernel/patches/freebsd/*.patch fi git -C "$src" checkout -q kw-wasm } # config(8) for the host: a yacc grammar, a lex scanner and C++. do_tools() { # Berkeley yacc, as the sources expect (bison's header breaks the C++ # files); macOS's yacc is one, Linux has it as byacc. YACC=${YACC:-$(command -v byacc || echo yacc)} c=$src/usr.sbin/config b=$tools/config rm -rf "$b" mkdir -p "$b" "$tools/bin" (cd "$b" && "$YACC" -d -o config.c "$c/config.y" && mv config.h y.tab.h && lex -o lang.c "$c/lang.l" && python3 -I -c 'import sys; d = open(sys.argv[1], "rb").read(); open("kernconf.c", "w").write("char kernconfstr[] = {" + ",".join(str(b) for b in d) + ",0};\n")' "$c/kernconf.tmpl" && for f in config.c lang.c kernconf.c "$c/mkheaders.c"; do cc -c -I. -I"$c" -include "$root/kernel/tools/freebsd-config-compat.h" \ -Wno-everything "$f" || exit 1 done && for f in main mkmakefile mkoptions; do c++ -std=c++17 -c -I. -I"$c" -include "$root/kernel/tools/freebsd-config-compat.h" \ -Wno-everything "$c/$f.cc" || exit 1 done && c++ -o "$tools/bin/config" ./*.o) ls -l "$tools/bin/config" } # build_kernel CONF DIR KWEMU OUT: config, make, lower to OUT. build_kernel() { mkdir -p "$2" (cd "$src/sys/wasm/conf" && "$tools/bin/config" -d "$2" "$1") (cd "$2" && unset CPPFLAGS CFLAGS LDFLAGS && KW_CLANG="$LLVM_BIN/clang" "$BMAKE" -m "$src/share/mk" -j8 \ MACHINE=wasm MACHINE_ARCH=wasm64 MACHINE_CPUARCH=wasm SRCTOP="$src" \ CC="$src/sys/wasm/conf/cc-wasm" CPP="$src/sys/wasm/conf/cc-wasm -E" \ LD="$WASM_LD" LLVM_NM="$LLVM_BIN/llvm-nm" OBJCOPY="$LLVM_BIN/llvm-objcopy" \ SIZE="$LLVM_BIN/llvm-size" AWK=awk KWEMU="$3") # The 32-bit-memory build, as for Linux and NetBSD: no memory64 needed. "$WASM_OPT" -g --memory64-lowering --table64-lowering -O2 --enable-bulk-memory \ --enable-sign-ext --enable-nontrapping-float-to-int --enable-mutable-globals \ --enable-threads "$2/kernel" -o "$4" ls -l "$2/kernel" "$4" } do_kernel() { # kwemu with its JIT (unkernel.kw_host_jit_*, which the SDK host serves), # and with atomics for GENERIC_MP's shared memory. (cd "$root" && zig build -Dkwemu-jit=true) (cd "$root" && zig build -Dkwemu-jit=true -Dkwemu-atomics=true --prefix vendor/build/kwemu-smp) cp "$root/include/kw_emu.h" "$src/sys/wasm/include/kw_emu.h" python3 -I "$root/kernel/tools/freebsd-atomic.py" > "$src/sys/wasm/include/atomic.h" mkdir -p "$out" build_kernel GENERIC "$compile" "$root/zig-out/lib/libkwemu.a" "$out/freebsd32.wasm" build_kernel GENERIC_MP "$compile_mp" "$root/vendor/build/kwemu-smp/lib/libkwemu.a" "$out/freebsd-mp32.wasm" } # The kernel and CLI flags for $CPUS: the MP kernel and --cpus N above one. kernel_args() { if [ "$CPUS" -gt 1 ]; then echo "--kernel $out/freebsd-mp32.wasm --cpus $CPUS" else echo "--kernel $out/freebsd32.wasm" fi } # root.fs: /rescue with sbin/init and bin/sh linked to it, uname(1) with # ld-elf.so.1, libc and libsys (the one dynamic program, for checks), /dev (devfs is # mounted there), /tmp, /etc. UFS1 with 4 KiB blocks: FreeBSD reads UFS1 # (NetBSD's makefs writes its own UFS2 variant), and one-page blocks keep # the buffer cache's buffers at their pages (flat kmem, vfs_bio.c). The # kernel reads it as the host's "initrd" into md0, the root. fetch_base() { mkdir -p "$out" set=$out/base.txz if [ ! -f "$set" ] || [ "$(shasum -a 256 "$set" | cut -d' ' -f1)" != "$BASE_SHA256" ]; then curl -fL -o "$set.tmp" "$BASE_URL" [ "$(shasum -a 256 "$set.tmp" | cut -d' ' -f1)" = "$BASE_SHA256" ] || { echo "base.txz: checksum mismatch" >&2; exit 1; } mv "$set.tmp" "$set" fi } do_rootfs() { fetch_base stage=$out/root rm -rf "$stage" mkdir -p "$stage" tar xf "$set" -C "$stage" ./rescue ./etc/master.passwd ./etc/group \ ./etc/pwd.db ./etc/spwd.db ./etc/login.conf \ ./usr/bin/uname ./libexec/ld-elf.so.1 ./lib/libc.so.7 ./lib/libsys.so.7 mkdir -p "$stage/dev" "$stage/tmp" "$stage/sbin" "$stage/bin" "$stage/root" ln "$stage/rescue/init" "$stage/sbin/init" ln "$stage/rescue/sh" "$stage/bin/sh" python3 -I - "$stage" > "$out/root.spec" <<'PY' import os, stat, sys root = sys.argv[1] print("/set uid=0 gid=0") print(". type=dir mode=0755") for dp, dns, fns in os.walk(root): rel = os.path.relpath(dp, root) for n in sorted(dns + fns): p = os.path.join(dp, n) r = "./" + (n if rel == "." else os.path.join(rel, n)) st = os.lstat(p) if stat.S_ISDIR(st.st_mode): print(f"{r} type=dir mode={'1777' if r == './tmp' else '0755'}") else: print(f"{r} type=file mode={stat.S_IMODE(st.st_mode):04o}") PY rm -f "$out/root.fs" "$MAKEFS" -t ffs -B le -o version=1,bsize=4096,fsize=4096,density=8192 \ -s 40m -F "$out/root.spec" "$out/root.fs" "$stage" ls -l "$out/root.fs" } # freebsd.img: the base set on UFS1 (4 KiB blocks, as root.fs), configured # for this machine: root on kwblk0, a getty on the console (kwcons), DHCP # on kwnet0 from the host's stack, no network services. Owners, modes and flags come from the tarball itself # (macOS may not keep them, and its file system folds case: a few man page # links whose names differ in case only are lost). do_image() { fetch_base stage=$out/image rm -rf "$stage" mkdir -p "$stage" tar xf "$out/base.txz" -C "$stage" 2>/dev/null || true chmod -R u+rwX "$stage" cat >> "$stage/etc/rc.conf" <<'RC' # unkernel (kernel/freebsd.sh image) hostname="freebsd" sendmail_enable="NONE" dumpdev="NO" cron_enable="NO" syslogd_flags="-ss" ifconfig_kwnet0="SYNCDHCP" # the host's stack: 10.0.2.15, gateway 10.0.2.2 RC cat > "$stage/etc/fstab" <<'FSTAB' /dev/kwblk0 / ufs rw 1 1 FSTAB cat >> "$stage/root/.profile" <<'PROFILE' # unkernel (kernel/freebsd.sh image): neofetch at login [ -x /usr/local/bin/neofetch ] && neofetch PROFILE # (sed -i differs between BSD and GNU sed: a new file instead.) sed -e 's#^console none unknown off secure#console "/usr/libexec/getty 3wire" vt100 on secure#' \ "$stage/etc/ttys" > "$stage/etc/ttys.new" && mv "$stage/etc/ttys.new" "$stage/etc/ttys" python3 -I - "$out/base.txz" "$stage" > "$out/image.spec" <<'PY' import os, stat, sys, tarfile tar, stage = sys.argv[1], sys.argv[2] meta = {} with tarfile.open(tar) as t: for m in t: name = m.name[2:] if m.name.startswith("./") else m.name meta[name] = m print("/set uid=0 gid=0") print(". type=dir mode=0755") for dp, dns, fns in os.walk(stage): rel = os.path.relpath(dp, stage) for n in sorted(dns + fns): r = n if rel == "." else os.path.join(rel, n) st = os.lstat(os.path.join(stage, r)) m = meta.get(r) mode = stat.S_IMODE(m.mode if m is not None else st.st_mode) own = f"uid={m.uid} gid={m.gid}" if m is not None else "uid=0 gid=0" if stat.S_ISLNK(st.st_mode): print(f"./{r} type=link {own} mode={mode:04o} link={os.readlink(os.path.join(stage, r))}") elif stat.S_ISDIR(st.st_mode): print(f"./{r} type=dir {own} mode={mode:04o}") else: print(f"./{r} type=file {own} mode={mode:04o}") PY rm -f "$out/freebsd.img" "$MAKEFS" -t ffs -B le -o version=1,bsize=4096,fsize=4096,density=16384 \ -s 2g -F "$out/image.spec" "$out/freebsd.img" "$stage" ls -l "$out/freebsd.img" install_pkgs } # The packages the image ships (IMAGE_PKGS; empty: none), installed by pkg # itself in one boot of the fresh image, which writes the disk in place (a # network is needed). Root's .profile runs neofetch at login. IMAGE_PKGS=${IMAGE_PKGS-neofetch} install_pkgs() { [ -n "$IMAGE_PKGS" ] || return 0 local log=$out/pkgs.log echo "image: installing $IMAGE_PKGS with pkg in a boot of freebsd.img ($log)" (cd "$root" && node --experimental-wasm-jspi --stack-trace-limit=40 js/cli.ts \ $(kernel_args) --initrd none --disk "$out/freebsd.img" \ --append "vfs.root.mountfrom=ufs:/dev/kwblk0" --distro none --mem 1024 \ --timeout 1500 --input "root {10}pkg install -y $IMAGE_PKGS && echo KW-PKGS-\"OK\"; shutdown -p now " --input-delay 120 < /dev/null > "$log" 2>&1) || true # The marker is quoted in the typed (echoed) command, whole in the output. grep -q '^KW-PKGS-OK' "$log" || { echo "image: installing $IMAGE_PKGS failed (see $log)" >&2; exit 1; } } # Multi-user from freebsd.img: rc, then getty and login on the console. # The SDK writes the image in place; --snapshot keeps the writes in memory. do_boot() { cd "$root" exec node --experimental-wasm-jspi --stack-trace-limit=40 js/cli.ts \ $(kernel_args) --initrd none --disk "$out/freebsd.img" \ --append "vfs.root.mountfrom=ufs:/dev/kwblk0" \ --distro none --mem "${MEM:-1024}" "$@" } # Single user (-s): init asks for a shell; RETURN takes /rescue/sh. do_run() { cd "$root" exec node --experimental-wasm-jspi --stack-trace-limit=40 js/cli.ts \ $(kernel_args) --initrd "$out/root.fs" \ --append "-s vfs.root.mountfrom=ufs:/dev/md0" \ --distro none --no-net --mem 256 "$@" } do_export() { rm -f "$root"/kernel/patches/freebsd/*.patch git -C "$src" format-patch -N -o "$root/kernel/patches/freebsd" "$FREEBSD_COMMIT..kw-wasm" } case "${1:-all}" in src) do_src ;; tools) do_tools ;; kernel) do_kernel ;; rootfs) do_rootfs ;; image) do_image ;; all) do_src; do_tools; do_kernel; do_rootfs; do_image ;; run) shift; do_run "$@" ;; boot) shift; do_boot "$@" ;; export) do_export ;; *) echo "usage: $0 src|tools|kernel|rootfs|image|all|run [ARGS]|boot [ARGS]|export" >&2; exit 2 ;; esac