#! /bin/bash
# set -xv
#=========================================================================
# Copyright (C) GemTalk Systems 1986-2016.  All Rights Reserved.
#
# Name - pstack
#
# Purpose - Generate C and Smalltalk call stacks for GemStone processes.
#
# $Id$
#
# Usages:
#
# Full C and Smalltalk stack printing, including args and temps of each
# stack frame:
#   pstack <pid>
# Brief stack, one line per frame:
#   pstack -b <pid>
# C full stacks only, omit smalltalk stack:
#   pstack -c <pid>
# Brief C stacks only:
#   pstack -C <pid>
# Print the help screen and exit:
#   pstack -h
#
# gdb must be in the user's PATH, and $GEMSTONE must be set.
#=========================================================================

usage(){
    echo "Usage: pstack pid"
    echo "       pstack <option> pid"
    echo "Where option is one (and only one) of the following:"
    echo "   -b   Brief mode.  Print brief C and Smalltalk stacks."
    echo "   -c   Print C stacks only.  Smalltalk stacks are not printed."
    echo "   -C   Same as -c except brief C stacks are printed."
    echo "   -h   Print this help screen and exit."
}

badArgs(){
    echo "[Error]: Missing or invalid argument(s) detected."
    usage
    exit 1
}    

printHelp(){
    usage
    exit 0
}

if [ "$1" = "-h" ]; then
    printHelp
fi

# Brief mode
if [ "$1" = "-b" ]; then
  if [ $# -ne 2 ] ; then
    badArgs
  fi
  pid=$2
  gcmd="$GEMSTONE/bin/pstackbrief.gdb"
elif [ "$1" = "-c" ]; then
  if [ $# -ne 2 ] ; then
    badArgs
  fi
# Full C stacks only  
  pid=$2
  gcmd="$GEMSTONE/bin/pstack_c_only.gdb"  
elif [ "$1" = "-C" ]; then
  if [ $# -ne 2 ] ; then
    badArgs
  fi
# *brief* C stacks only  
  pid=$2
  gcmd="$GEMSTONE/bin/pstack_brief_c_only.gdb"
else
# Normal mode    
  if [ $# -ne 1 ] ; then
    badArgs
  fi
  pid=$1
  gcmd="$GEMSTONE/bin/pstack.gdb"
fi

gdb=gdb
type $gdb
errcode=$?
if [ $errcode -ne 0 ] ; then
    echo "[Error]: Cannot find $gdb in path $PATH"
    exit $errcode
fi

# Make sure $pid is a positive integer
case $pid in
    ''|*[!0-9]*) pidOK=0 ;;
    *) pidOK=1 ;;
esac

if [ $pidOK -eq 0 ]; then
    echo "[Error]: The given process ID '$pid' is not a positive integer."
    badArgs
fi

## Invoke GDB, filter output
# --nw prevents GUI interface to GDB, if installed
# --nx prevents user's .gdbinit from being run
# --batch suppresses version/copyright header and terminates GDB when
#   input file exhausted
# --pid attaches to the given process
# read commands from stdin redirected to file $gcmd
echo "===--- start gdb stacks"
date
$gdb --nw --nx --pid=$pid < $gcmd | \
  grep -Ev '^\(gdb\)|^Reading|^Loaded|No such file or directory\.$'
#"No such file or directory" regularly appears on Mac, not a real problem
echo "===--- end gdb stacks"

