#!/bin/sh

dir=`dirname $0`
dir=`cd $dir; /bin/pwd`

suppressions=` cd $dir/../design/scripts ; /bin/pwd `

valgrind="valgrind --suppressions=$suppressions/valgrind-python.supp --suppressions=$suppressions/valgrind-python-leaks.supp --suppressions=$suppressions/gps.supp --track-fds=yes --num-callers=30"

# use --db-attach=yes        to attach to a debugger for every error found
# use --gen-suppressions=all to generate a suppression file
# use --show-reachable=yes   to show unfreed blocks for which we still have a handle
# use --log-file=gps_valgrind.$$ to log the output


## See http://www.lrz-muenchen.de/services/software/programmierung/valgrind/html_3.0/ms-manual.html

## Modes that can be used when running this script:
## memcheck : check pointers
## debug    : check pointers, in debug server mode
## leaks     : detect memory leaks
## leaks2:   : same as above, but shows how to create a suppression file
## massif   : check heap usage
## addrcheck: check pointers usage, same as memcheck but doesn't do
##            "undefined-value checks". Twice as fast though
## cachegrind: cache simulator
## callgrind: call graph tracing for cachegrind
##            This is a profiling tool. Use callgrind-control to get partial
##            dumps or find out the backtrace

mode=${1:-memcheck}
shift

gps=${1:-$dir/obj/gps}
shift

G_SLICE=always-malloc
G_DEBUG=gc-friendly,resident-modules
export G_SLICE G_DEBUG

# Activate special behavior in GPS (among others reset entities database
# on exit)
export VALGRIND=yes

case $mode in
   leaks2)   args="--tool=memcheck --leak-check=full --gen-suppressions=all" ;;
   leaks)    args="--tool=memcheck --leak-check=full --leak-resolution=med" ;;
   leaks3)   args="--tool=memcheck --leak-check=full --show-reachable=yes" ;;
   memcheck) args="--tool=memcheck";;
   debug) args="--tool=memcheck --vgdb=yes --vgdb-error=0";;
   massif)   args="--tool=massif --depth=5 --format=html --alloc-fn=__gnat_malloc \
                   --alloc-fn=PyObject_Malloc --alloc-fn=g_malloc --alloc-fn=__gnat_realloc \
                   --alloc-fn=g_realloc --alloc-fn=g_try_malloc --alloc-fn=g_malloc0 \
                   --alloc-fn=g_mem_chunk_alloc --alloc-fn=_PyObject_GC_Malloc" ;;
   callgrind) args="--tool=callgrind --dump-instr=yes --trace-jump=yes";;
   *) echo "Invalid first argument: expecting leaks, memcheck or massif"
      exit -1;;
esac

$valgrind $args $gps "$@" 2>&1 | tee gps_valgrind.$$
