#!/usr/bin/env bash

set -euo pipefail

if [ $# == 0 ] || [ "$1" == '--help' ] || [ "$1" == '-h' ]; then
  cat <<USAGE
Usage: $0 your-program [your-program-options]

Runs a binary (that has been compiled with asan) using the correct symbolizer
location and suppressions file.
USAGE

  exit 1
fi

# NOTE: script_directory is going to look different in run/test.
script_directory="$(dirname "${BASH_SOURCE[0]}")"

base_dir="${script_directory}/../.."

if ! [[ -f "$base_dir"/ci/runners/asan_suppressions.txt ]]; then
  base_dir="$script_directory"/asan.runfiles/zoox
  if ! [[ -f "$base_dir"/ci/runners/asan_suppressions.txt ]]; then
    echo Failed to find ASAN runfiles!
    exit 1
  fi
fi

# Template variable replaced by expand_template.
extra_asan_options="{{EXTRA_ASAN_OPTIONS}}"

asan_suppressions_file="${base_dir}/ci/runners/asan_suppressions.txt"
lsan_suppressions_file="${base_dir}/ci/runners/lsan_suppressions.txt"
ld_preload="${base_dir}/../gcc_7_4/usr/lib/x86_64-linux-gnu/libasan.so.4"

# libasan.so must be the first library loaded, so we LD_PRELOAD it.
LD_PRELOAD=${ld_preload} \
  ASAN_OPTIONS=symbolize=1:suppressions="$asan_suppressions_file""${extra_asan_options:-}" \
  LSAN_OPTIONS=suppressions="$lsan_suppressions_file" \
  "$@"
