#!/bin/sh

# efence -- wrapper to run a program under gdb and electric-fence

# Copyright 2003, 2007 Kevin Ryde
#
# This program is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the Free
# Software Foundation; either version 2, or (at your option) any later
# version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
# or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
# for more details.
#
# You can get a copy of the GNU General Public License online at
# <http://www.gnu.org/licenses/>.


# Version 1 - the first version.
#
VERSION=1

protect='set environment EF_PROTECT_BELOW=0'
help=no

while [ $# -ne 0 ]
do
  case "$1" in
    --below)
      protect='set environment EF_PROTECT_BELOW=1'
      shift
      continue
      ;;
    --help)
      help=yes
      break
      ;;
    --version)
      echo "efence version $VERSION"
      exit 0
      ;;
    --)
      shift
      break
      ;;
    -*)
      echo "efence: unrecognised option: $1" exit 1
      ;;
    *)
      break
      ;;
  esac
done

if [ $# -eq 0 -o $help = yes ]
then
  cat <<'EOF'
Usage: efence [--options] program [args...]
  --below    set EF_PROTECT_BELOW=1 for redzones below instead of above
  --help     print this help message
  --version  print version number
  --         end option processing

efence is a convenient way to run a program under gdb with electric-fence
enabled.

    efence my-program -x foo.txt

The program runs with /usr/lib/libefence.so added to LD_PRELOAD, and command
line arguments passed through to the program.  The redzones electric-fence
creates will result in a SIGSEGV if the program goes outside the bounds of
its blocks, and gdb catches that and lets you see the offending instruction
etc in the usual way.

A --below option can set EF_PROTECT_BELOW=1 to have redzones below instead
of above blocks.  Eg.

    efence --below my-program

See http://perens.com/FreeSoftware/ElectricFence/ and "man libefence" for
more on electric-fence.

This script home page: http://www.geocities.com/user42_kevin/efence/index.html
EOF
  if [ $help = yes ]; then
    exit 0   # requested --help
  else
    exit 1   # no program arg
  fi
fi

exec gdb \
 -eval-command "set environment LD_PRELOAD=/usr/lib/libefence.so $LD_PRELOAD" \
 -eval-command "$protect" \
 -eval-command 'echo
' \
 -eval-command 'show environment LD_PRELOAD' \
 -eval-command 'show environment EF_PROTECT_BELOW' \
 -eval-command 'echo
Type "run" to start
' \
 --args "$@"
