#!/bin/sh
# TODO include a -p option to attach to a process
usage () {
    echo  Usage:
    echo "    $0 [ -L N | -expr PROG@FUNC@EXPR FILTER ] PROGRAM args..."
    echo  runs PROGRAM under the gdb-based PCT statistical profiling system.
}
if [ $# -lt 1 ]; then usage; exit 1; fi

OUT=/tmp/pct/gdb.$$; echo "PCT output sent to $OUT"
mkdir -p $OUT

if [ $1 = "-L" ]; then
    Levels=$2
    shift 2
cat >> $OUT/script.dbctl <<EOF
EXEC() ".*" {
#include "gdbprof_prol.dbctl"
  PATTERN_GROUP("default")  {
    PATTERN("1") "signal-name=\"SIGVTALRM\"" |  OUTPUT("address") {
	"where $Levels"| OUTPUT("where");
	"continue";
    }
#include "gdbprof_epil.dbctl"
  }
}
EOF
    dbctl -c $OUT/script.dbctl -o $OUT "$@"
    col=2
    n=$Levels
    cols="2"
    while [ $n -gt 1 ]; do
	col=`expr $col + 4`
	cols="${cols},${col}"
	n=`expr $n - 1`
    done
    cat $OUT/*/where | where-simp | dblog2hist $cols $cols |sort -n|pct-%
elif [ $1 = "-expr" ]; then
    shift 1
    eval `echo $1 | sed -e 's/^/prog=/' -e 's/@/;func=/' -e 's/@/;expr=/'`
    shift 1
    filter=$1
    shift 1
cat >> $OUT/script.dbctl <<EOF
EXEC() "$prog" {
#include "gdbprof_prol.dbctl"
  PATTERN_GROUP("default")  {
    PATTERN("1") "signal-name=\"SIGVTALRM\"" |  OUTPUT("address") {
    	"info frame" | MATCH("Functions");
	"continue";
    }
#include "gdbprof_epil.dbctl"
  }
  PATTERN_GROUP("Functions")  {
    PATTERN("1") "$func"  {
	"print $expr" | OUTPUT("expr");
    }
  }
}
EOF
    dbctl -c $OUT/script.dbctl -o $OUT "$@"
    for i in $OUT/*/expr; do
	$filter < $i > $i.vals
    done
else
    dbctl -o $OUT "$@"
    cat $OUT/*/address | addr-simp | dblog2hist 0 2|pct-sort 1|pct-fold|sort -n|pct-%
fi
