#!/bin/bash
# Reproduces the ANGLE-Vulkan cross-ShareGroup VkSampler lifetime bug.
#
# The bug: with EGL_ANGLE_display_texture_share_group, a TextureVk shared at
# display level can carry a SharedSamplerPtr allocated from one ShareGroupVk's
# SamplerCache while being sampled from a different ShareGroupVk's context.
# When the owning ShareGroup is torn down, the sampler is either destroyed
# directly (if unique()) or moved to Renderer::mOrphanedSamplers and reaped by
# cleanupOrphanedSamplers() purely on CPU refcount – with no queue-serial /
# ResourceUse gate.  If the other context still has a submitted command buffer
# whose COMBINED_IMAGE_SAMPLER descriptor references that VkSampler,
# vkDestroySampler() is called while the sampler is in use, violating
# VUID-vkDestroySampler-sampler-01082.
#
# Detection: Vulkan Validation Layers.  This is a driver-side stale handle, so
# ASAN does not catch it directly (the descriptor write copies the raw handle,
# not a pointer that ASAN tracks).
set -e

CHROMIUM_SRC="${CHROMIUM_SRC:-/chromium/chromium/src}"
OUT="${OUT:-$CHROMIUM_SRC/out/asan}"

cd "$(dirname "$0")"

echo "[*] Applying angle_end2end_tests POC patch ..."
( cd "$CHROMIUM_SRC/third_party/angle" && git apply --whitespace=nowarn ) < angle-end2end-test.patch

echo "[*] Building angle_end2end_tests ..."
( cd "$CHROMIUM_SRC" && autoninja -C "$OUT" angle_end2end_tests )

echo "[*] Running POC tests under SwiftShader-Vulkan with the Khronos validation layer force-enabled ..."
cd "$OUT"
VK_ICD_FILENAMES="$OUT/vk_swiftshader_icd.json" \
VK_LAYER_PATH="$OUT/angledata" \
VK_INSTANCE_LAYERS=VK_LAYER_KHRONOS_validation \
  ./angle_end2end_tests \
    --gtest_filter='EGLContextSharingTest.DisplayShareGroupSamplerInFlightWhenOwningShareGroupDestroyed/ES2_Vulkan:EGLContextSharingTest.DisplayShareGroupOrphanedSamplerReapedWhileInFlight/ES2_Vulkan' \
  2>&1 | tee poc-run.log

echo
echo "[*] Expected: two 'VUID-vkDestroySampler-sampler-01082' validation errors above."
echo "[*] To revert the test patch:"
echo "    ( cd $CHROMIUM_SRC/third_party/angle && git checkout -- src/tests/egl_tests/EGLContextSharingTest.cpp )"
