#!/usr/bin/env -S -u LD_PRELOAD /bin/sh
# Compilers abort or spend the test budget inside LeakSanitizer when the
# suite has preloaded libasan for Python. Drop it for this process only.
# Do not spawn dirname. Under the preloaded sanitizer that coreutils
# binary leaks and aborts before this wrapper can drop LD_PRELOAD.
case $0 in
  */*) _wrap_dir=${0%/*} ;;
  *) _wrap_dir=. ;;
esac
here=$(CDPATH= cd -- "$_wrap_dir" && pwd)
real=${REAL_CC:-}
if [ -z "$real" ]; then
  old_ifs=$IFS
  IFS=:
  for dir in $PATH; do
    [ "$dir" = "$here" ] && continue
    if [ -x "$dir/cc" ]; then
      real=$dir/cc
      break
    fi
  done
  IFS=$old_ifs
fi
if [ -z "$real" ]; then
  echo "cc is not on PATH" >&2
  exit 1
fi
unset LD_PRELOAD
# libseams built with clang -fsanitize=thread has undefined __tsan_*
# symbols. gcc cannot satisfy them. Link the clang runtime the library
# was built with.
if [ -n "${TSAN_RUNTIME:-}" ] && [ -f "$TSAN_RUNTIME" ]; then
  rtdir=$(dirname "$TSAN_RUNTIME")
  link=1
  for arg in "$@"; do
    case $arg in
      -c|-E|-M|-MM) link=0 ;;
    esac
  done
  if [ "$link" = 1 ]; then
    # clang -fopenmp asks for libomp, which lives next to Archer.
    omplib=
    if [ -n "${OMP_TOOL_LIBRARIES:-}" ] && [ -f "$OMP_TOOL_LIBRARIES" ]; then
      omplib=$(dirname "$OMP_TOOL_LIBRARIES")
    fi
    if [ -n "$omplib" ]; then
      exec clang -fsanitize=thread -shared-libsan -Wl,-rpath,"$rtdir" \
        -L"$omplib" -Wl,-rpath,"$omplib" "$@"
    fi
    exec clang -fsanitize=thread -shared-libsan -Wl,-rpath,"$rtdir" "$@"
  fi
  exec clang -fsanitize=thread "$@"
fi
# A snippet that links the sanitized libseams has to be instrumented
# too. Otherwise the address runtime faults while binding C++ symbols.
if [ -n "${ASAN_TEST_PRELOAD:-}" ] && [ -f "$ASAN_TEST_PRELOAD" ]; then
  link=1
  needs=0
  for arg in "$@"; do
    case $arg in
      -c|-E|-M|-MM) link=0 ;;
      -lseams|-lseams_lang|-llammps) needs=1 ;;
    esac
  done
  if [ "$link" = 1 ] && [ "$needs" = 1 ]; then
    exec "$real" -fsanitize=address,undefined "$@"
  fi
fi
exec "$real" "$@"
