#!/usr/bin/env bash
#
# build.sh -- build every ACFG variant this machine's toolchain can produce,
#             and say clearly which ones it cannot.
#
# Chapter 70 -- Vulnerability Research, examples/
#
# PURPOSE
#   Turn the three C files in this directory into fuzzable binaries. There are
#   four possible build variants and almost no machine has all four, so this
#   script probes rather than assumes, and reports each variant as BUILT,
#   SKIPPED (with the reason) or FAILED.
#
#     1. host + libFuzzer + ASan/UBSan   -- needs clang
#     2. host + standalone + ASan/UBSan  -- needs clang OR gcc
#     3. Android + libFuzzer + ASan      -- needs the NDK; runs on an emulator
#     4. Android + standalone + ASan     -- needs the NDK; runs on an emulator
#
# USAGE
#   ./build.sh                 build everything possible into $OUT
#   ./build.sh replay          build, then replay ./crashers/* against both
#                              the vulnerable and the fixed parser
#   OUT=/tmp/mybuild ./build.sh
#
#   Set NDK to your NDK root to enable variants 3 and 4, for example:
#     export NDK="$HOME/Android/Sdk/ndk/25.2.9519653/toolchains/llvm/prebuilt/linux-x86_64"
#
# REQUIREMENTS
#   bash, a C11 compiler with AddressSanitizer, python3 (to generate the seed
#   corpus). Everything else is optional and detected.
#
# WHERE IT BUILDS
#   Into $OUT, which defaults to a directory OUTSIDE this repository
#   (${TMPDIR:-/tmp}/acfg-build). Nothing this script produces should ever be
#   committed: binaries, corpora and crash files are all on the repository's
#   artefact blocklist. If you change OUT, keep it out of the tree.
#
# WHAT THIS WILL NOT TELL YOU
#   - Whether your fuzzing environment is any good. It checks that a compiler
#     accepts the flags, not that the resulting campaign is meaningful.
#   - Whether a crash matters. That is ../scripts/triage-asan.py and section 8.
#   - Anything about your device. This script never touches adb. Running the
#     Android variants on hardware is a manual, deliberate step described in
#     ../labs/lab-02-harness-and-triage.md, and the chapter's position is that
#     you do it on an emulator or a device you own and can afford to lose --
#     never on a phone you depend on.

set -u

OUT="${OUT:-${TMPDIR:-/tmp}/acfg-build}"
HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

mkdir -p "$OUT/corpus" "$OUT/findings"

built=0
skipped=0
failed=0

say()  { printf '%s\n' "$*"; }
ok()   { printf '  [BUILT]   %s\n' "$*"; built=$((built+1)); }
skip() { printf '  [SKIPPED] %s\n' "$*"; skipped=$((skipped+1)); }
bad()  { printf '  [FAILED]  %s\n' "$*"; failed=$((failed+1)); }

say "ACFG build -- output directory: $OUT"
say ""

# ---------------------------------------------------------------------------
# Probe the toolchain. Report what is present rather than guessing.
# ---------------------------------------------------------------------------

HAVE_CLANG=0
HAVE_GCC=0
HAVE_LIBFUZZER=0

command -v clang  >/dev/null 2>&1 && HAVE_CLANG=1
command -v gcc    >/dev/null 2>&1 && HAVE_GCC=1

if [ "$HAVE_CLANG" = "1" ]; then
    # -fsanitize=fuzzer needs the libclang_rt.fuzzer runtime, which several
    # distributions package separately from clang itself. Compiling a
    # three-line program is the only reliable test; checking the clang version
    # is not, and neither is looking for the .a file, whose path moves.
    cat > "$OUT/.probe.c" <<'PROBE'
#include <stdint.h>
#include <stddef.h>
int LLVMFuzzerTestOneInput(const uint8_t *d, size_t n) { (void)d; (void)n; return 0; }
PROBE
    if clang -fsanitize=fuzzer "$OUT/.probe.c" -o "$OUT/.probe" >/dev/null 2>&1; then
        HAVE_LIBFUZZER=1
    fi
    rm -f "$OUT/.probe.c" "$OUT/.probe"
fi

say "toolchain probe:"
say "  clang        : $([ $HAVE_CLANG = 1 ] && clang --version | head -1 || echo 'not found')"
say "  gcc          : $([ $HAVE_GCC = 1 ] && gcc --version | head -1 || echo 'not found')"
say "  libFuzzer    : $([ $HAVE_LIBFUZZER = 1 ] && echo 'available' || echo 'NOT available')"
say "  NDK          : ${NDK:-not set}"
say ""

COMMON="-std=c11 -Wall -Wextra -Werror -g -O1 -fno-omit-frame-pointer -I$HERE"

# ---------------------------------------------------------------------------
# Variant 1 and 2 -- host builds
# ---------------------------------------------------------------------------

say "host builds:"

if [ "$HAVE_LIBFUZZER" = "1" ]; then
    for v in vulnerable fixed; do
        if clang $COMMON -fsanitize=fuzzer,address,undefined \
                 -fsanitize-address-use-after-scope \
                 "$HERE/fuzz-acfg.c" "$HERE/acfg-$v.c" \
                 -o "$OUT/fuzz_${v}_libfuzzer" 2>"$OUT/.err"; then
            ok "fuzz_${v}_libfuzzer  (clang, libFuzzer + ASan + UBSan)"
        else
            bad "fuzz_${v}_libfuzzer"; sed 's/^/            /' "$OUT/.err"
        fi
    done
else
    skip "fuzz_*_libfuzzer  -- no clang with -fsanitize=fuzzer on this machine"
fi

HOSTCC=""
[ "$HAVE_CLANG" = "1" ] && HOSTCC=clang
[ -z "$HOSTCC" ] && [ "$HAVE_GCC" = "1" ] && HOSTCC=gcc

if [ -n "$HOSTCC" ]; then
    for v in vulnerable fixed; do
        if $HOSTCC $COMMON -fsanitize=address,undefined -DACFG_STANDALONE \
                 "$HERE/fuzz-acfg.c" "$HERE/acfg-$v.c" \
                 -o "$OUT/fuzz_${v}_standalone" 2>"$OUT/.err"; then
            ok "fuzz_${v}_standalone  ($HOSTCC, ASan + UBSan, no coverage feedback)"
        else
            bad "fuzz_${v}_standalone"; sed 's/^/            /' "$OUT/.err"
        fi
    done
else
    skip "fuzz_*_standalone  -- no host C compiler found"
fi

# ---------------------------------------------------------------------------
# Variant 3 and 4 -- Android cross builds
#
# Note the ABI choice. x86_64 is the default because that is what a desktop
# emulator runs, and an emulator is where a sane person fuzzes. Set ABI=arm64
# only if you have a physical device you are willing to destabilise.
# ---------------------------------------------------------------------------

say ""
say "Android builds:"

ABI="${ABI:-x86_64}"
API="${API:-24}"

case "$ABI" in
    x86_64) TRIPLE="x86_64-linux-android$API" ;;
    arm64)  TRIPLE="aarch64-linux-android$API" ;;
    arm)    TRIPLE="armv7a-linux-androideabi$API" ;;
    x86)    TRIPLE="i686-linux-android$API" ;;
    *)      TRIPLE="" ;;
esac

if [ -z "${NDK:-}" ]; then
    skip "android_*  -- NDK not set; export NDK=<ndk>/toolchains/llvm/prebuilt/<host>"
elif [ -z "$TRIPLE" ]; then
    bad "android_*  -- unknown ABI '$ABI'"
elif [ ! -x "$NDK/bin/${TRIPLE}-clang" ] && [ ! -f "$NDK/bin/${TRIPLE}-clang.cmd" ]; then
    skip "android_*  -- $NDK/bin/${TRIPLE}-clang not found"
else
    NDKCC="$NDK/bin/${TRIPLE}-clang"
    [ -x "$NDKCC" ] || NDKCC="$NDK/bin/${TRIPLE}-clang.cmd"

    for v in vulnerable fixed; do
        # -fsanitize=fuzzer,address for Android. Two Android-specific points:
        #
        #  * ASan on Android is a SHARED runtime. The binary will not start
        #    unless libclang_rt.asan-<abi>-android.so sits next to it or on
        #    LD_LIBRARY_PATH. Forgetting this produces "library not found" and
        #    a great deal of confusion, so lab 02 copies it explicitly.
        #  * -static-libsan is not available for Android in NDK r25.
        if "$NDKCC" $COMMON -fsanitize=fuzzer,address \
                 "$HERE/fuzz-acfg.c" "$HERE/acfg-$v.c" \
                 -o "$OUT/android_${ABI}_fuzz_${v}" 2>"$OUT/.err"; then
            ok "android_${ABI}_fuzz_${v}  (NDK clang, libFuzzer + ASan, API $API)"
        else
            bad "android_${ABI}_fuzz_${v}"; sed 's/^/            /' "$OUT/.err"
        fi
    done

    # The ASan runtime the binaries above need at run time.
    rt=$(find "$NDK/lib64/clang" "$NDK/lib/clang" -name "libclang_rt.asan-*-android.so" 2>/dev/null | head -20)
    if [ -n "$rt" ]; then
        printf '%s\n' "$rt" | while read -r f; do cp -f "$f" "$OUT/" 2>/dev/null; done
        say "  [NOTE]    copied the ASan shared runtimes into $OUT --"
        say "            push the one matching your ABI alongside the binary."
    fi
fi

rm -f "$OUT/.err"

# ---------------------------------------------------------------------------
# Seed corpus. Three valid blobs plus one empty file.
#
# A corpus of valid inputs is worth more than any amount of extra CPU. A fuzzer
# starting from an empty file has to rediscover the four magic bytes before it
# reaches a single line of the record loop; starting from a valid blob it is
# already past the header on execution one. Section 7.5.
# ---------------------------------------------------------------------------

say ""
say "seed corpus:"

if command -v python3 >/dev/null 2>&1; then
    python3 -B - "$OUT/corpus" <<'PY'
import os, struct, sys
d = sys.argv[1]
os.makedirs(d, exist_ok=True)

def blob(recs, version=1, count=None):
    n = len(recs) if count is None else count
    b = b'ACFG' + struct.pack('<HH', version, n)
    for t, name, val in recs:
        b += struct.pack('<BBH', t, len(name), len(val)) + name + val
    return b

seeds = {
    'seed-one-record.bin':  blob([(1, b'hello', b'abc')]),
    'seed-two-records.bin': blob([(1, b'debug', b'\x01'),
                                  (2, b'level', b'\x03\x00\x00\x00')]),
    'seed-zero-records.bin': blob([]),
    'seed-all-types.bin':   blob([(1, b's', b'x'), (2, b'i', b'\x00\x00\x00\x01'),
                                  (3, b'b', b'\x01'), (4, b'z', b'\xde\xad\xbe\xef')]),
    'seed-empty.bin':       b'',
}
for name, data in seeds.items():
    with open(os.path.join(d, name), 'wb') as f:
        f.write(data)
    print('  %-24s %3d bytes' % (name, len(data)))
PY
else
    skip "seed corpus -- python3 not found"
fi

# ---------------------------------------------------------------------------
# Optional: replay the known crashers against both parsers.
# ---------------------------------------------------------------------------

if [ "${1:-}" = "replay" ]; then
    say ""
    say "replay:"
    if [ ! -d "$HERE/crashers" ]; then
        python3 -B - "$OUT/crashers" <<'PY'
import os, struct, sys
d = sys.argv[1]; os.makedirs(d, exist_ok=True)
def blob(recs, version=1):
    b = b'ACFG' + struct.pack('<HH', version, len(recs))
    for t, name, val in recs:
        b += struct.pack('<BBH', t, len(name), len(val)) + name + val
    return b
open(os.path.join(d,'crash-count1-nlen58.bin'),'wb').write(blob([(1, b'A'*58, b'')]))
open(os.path.join(d,'crash-count1-nlen32.bin'),'wb').write(blob([(1, b'A'*32, b'')]))
open(os.path.join(d,'crash-count2-nlen200.bin'),'wb').write(blob([(1, b'B'*200, b''), (2, b'x', b'')]))
print('  generated 3 reproducers in', d)
PY
        CR="$OUT/crashers"
    else
        CR="$HERE/crashers"
    fi

    for f in "$CR"/*.bin; do
        say ""
        say "  --- $(basename "$f") against the VULNERABLE parser ---"
        "$OUT/fuzz_vulnerable_standalone" "$f" 2>&1 | sed 's/^/    /' | head -25
        say "  --- $(basename "$f") against the FIXED parser ---"
        "$OUT/fuzz_fixed_standalone" "$f" 2>&1 | sed 's/^/    /' | head -25
    done
fi

say ""
say "built=$built skipped=$skipped failed=$failed"
say ""
say "Next: ../labs/lab-02-harness-and-triage.md walks the whole loop --"
say "campaign, crash, reproducer, triage, reachability verdict."

[ "$failed" -eq 0 ]
