#!/usr/bin/env bash
# Builds repro.cpp against a FIT C++ SDK checkout under AddressSanitizer,
# reads each of make_fault_files.py's files with it, and says for each whether
# the SDK read past a buffer or through a null pointer.
#
#   prove.sh [sdk-dir]        the SDK's root, holding src/; this tree's
#                             fit-cpp-sdk/ when none is given
#
# Needs clang++ and python3. Exits 0 when any fault is shown, 1 when every
# file is read cleanly, 2 when the build fails.
set -uo pipefail

here="$(cd "$(dirname "$0")" && pwd)"
sdk="$(cd "${1:-$here/../../fit-cpp-sdk}" && pwd)"
work="$(mktemp -d)"
trap 'rm -rf "$work"' EXIT

compiler="$(command -v clang++-18 || command -v clang++)"
python3 "$here/make_fault_files.py" "$work" > /dev/null
if ! "$compiler" -std=c++17 -g -O1 -fsanitize=address -fno-omit-frame-pointer \
        -I"$sdk/src" "$here/repro.cpp" "$sdk"/src/*.cpp -o "$work/repro" 2> "$work/build.txt"; then
    tail -20 "$work/build.txt"
    exit 2
fi

shown=0
for file in short-field.fit enum-timestamp.fit empty-developer.fit old-device.fit repeated-developer.fit; do
    echo "== $file"
    ASAN_OPTIONS=halt_on_error=1 "$work/repro" "$work/$file" > "$work/run.txt" 2>&1
    grep -E "CheckIntegrity|Read:|ERROR: AddressSanitizer|READ of size|^    #[0-3] |located" "$work/run.txt" |
        sed -E "s#$sdk/##g; s# \(/tmp[^)]*\)##"
    if grep -q "ERROR: AddressSanitizer" "$work/run.txt"; then
        echo "  the SDK at $sdk reads past a buffer, through a null pointer or freed memory on $file"
        shown=1
    else
        echo "  read without a fault"
    fi
done
[ "$shown" = 1 ] && exit 0
exit 1
