#!/bin/bash

# Compare the IR generated for the shipped
# tools between two bpftrace builds
#

set -o pipefail
set -e
set -u

if [[ "$#" -ne 3 ]]; then
  echo "Compare IR generated between two bpftrace builds"
  echo ""
  echo "USAGE:"
  echo "$(basename $0) <bpftrace_A> <bpftrace_B> <tooldir>"
  echo ""
  echo "EXAMPLE:"
  echo "$(basename $0) bpftrace bpftrace_master /vagrant/tools"
  echo ""
  exit 1
fi

TOOLDIR=$3
BPF_A=$(command -v "$1") || ( echo "ERROR: $1 not found"; exit 1 )
BPF_B=$(command -v "$2") || ( echo "ERROR: $2 not found"; exit 1 )
[[ -d "$TOOLDIR" ]] || (echo "tooldir does not appear to be a directory: ${TOOLDIR}"; exit 1)

# Set to 1 to only compare result after opt
AFTER_OPT=0

if [ $AFTER_OPT -eq 1 ]; then
  FLAGS="-d"
else
  FLAGS="-dd"
fi

TMPDIR=$(mktemp -d)
[[ $? -ne 0 || -z $TMPDIR ]] && (echo "Failed to create tmp dir"; exit 10)

cd $TMPDIR
set +e

function hash() {
    file="${1}"
    sha1sum "${1}" | awk '{print $1}'
}

function fix_timestamp() {
    cat $@ | awk '/(add|sub) i64 %get_ns/ { $NF = ""} {print}'
}

for script in ${TOOLDIR}/*.bt; do
    s=$(basename ${script/.bt/})
    echo "Checking $s"
    2>&1 $BPF_A "$FLAGS" "$script" | fix_timestamp > "a_${s}"
    2>&1 $BPF_B "$FLAGS" "$script" | fix_timestamp > "b_${s}"
    if [ $? -ne 0 ]; then
        echo "###############################"
        echo "bpftrace failed on script: ${s}"
        echo "###############################"
        continue
    fi
    if [[ $(hash "a_${s}") != $(hash "b_${s}")  ]]; then
        echo "Change detected for script: ${s}"
        diff -b -u "a_${s}" "b_${s}"
    fi
done

[[ -n ${TMPDIR} ]] && rm -rf "${TMPDIR}"

Add script to compare tool codegen between builds
Add script to compare tool codegen between builds

This script makes it easier to test for unexpected changes in the code
generated for our "real world" tools.

It takes two bpftrace builds (binary) and a directory containing tools
as arguments and prints the diff for each of the tools in the tool
directory, e.g:

```
$ sudo /vagrant/scripts/compare_tool_codegen.sh bpftrace bpftrace_master /vagrant/tools/
Checking bashreadline
Checking biolatency
Checking biosnoop
Change detected for script: biosnoop
--- a_biosnoop	2019-11-07 15:48:23.987667861 +0000
+++ b_biosnoop	2019-11-07 15:48:24.027668859 +0000
@@ -361,7 +361,8 @@
   %1 = bitcast i64* %"$now" to i8*
   call void @llvm.lifetime.start.p0i8(i64 -1, i8* %1)
   store i64 0, i64* %"$now"
-  %strcmp.result = alloca i64
+  %strcmp.char = alloca i8
+  %strcmp.result = alloca i8
   %lookup_elem_val21 = alloca [16 x i8]
```

It's intended to be used as an extra, manual, verification step to
make sure our tools aren't unexpectedly impacted by a change.
