#!/bin/bash -x
# we are working by default with gcc 6
GCC_VERSION=6
# TODO
# maybe blacklist some params passed to gcc, to avoid conflicting params 
# removed -fno-common, since it cause errors, when extern or static isnt used in globals
PARAMS=(-fsanitize=address,undefined -fsanitize-recover -g -Warray-bounds -fno-omit-frame-pointer -U_FORTIFY_SOURCE)

# passing pthread always, even when its not necessary is a quick fix for
# https://gcc.gnu.org/bugzilla/show_bug.cgi?id=69443

# $1 array to be checked
# $2 = the param to be added
function add_param_if_needed {
  a=("$@")
  ((last_idx=${#a[@]} - 1)) 
  b=${a[last_idx]} 
  unset a[last_idx]
  (for e in "$a"; do [[ "$e" == "$b" ]] && exit 0; done) || PARAMS+=($b)
}

if [ -r /etc/gcc-sanitizer.default ]; then
        . /etc/gcc-sanitizer.default
fi

if [ "$0" == "/usr/bin/g++" ]; then
        CC=$(which g++-$GCC_VERSION)
        PARAMS+=(-lasan)
else # default case is gcc.There are more cases to catch? clang maybe?
        CC=$(which gcc-$GCC_VERSION)
fi

# some flags which we should ignore 
for flag in "-E" "-print-prog-name=ld"; do	
	if (for e in "$@"; do [[ "$e" == "$flag" ]] && exit 0; done); then
		exec $CC "$@"
	fi
done


# in those cases, we should not try to set ASAN
if ! echo "$@" | grep -q '__KERNEL__\|-nostdlib\|-static'; then
    # not working as expected
	# PC=()
    # for d in "$@"; do [ "$d" != "-D_FORTIFY_SOURCE=2" ] && PC+=("$d"); done
    # $CC ${PARAMS[@]} "${PC[@]}" -Wl,-lasan,-lpthread,-lubsan
    $CC ${PARAMS[@]} "$@" -Wl,-lasan,-ldl,-lpthread,-lubsan
else
    $CC "$@"
fi
