#! /bin/bash
# Copyright (C) GemTalk Systems 1986-2014.  All Rights Reserved.
#
# GemStone pstack -- print the stack for a given PID using GDB.
# usage: 
# Full stack printing including args and temps of each frame
#   pstack <pid>
# Brief stack, one line per frame 
#   pstack -b <pid>
#
# GDB must be in the user's PATH, and $GEMSTONE must be valid

args="ok"

if [ "$1" = "-b" ]; then
  if [ $# -ne 2 ] ; then
    args="bad"
  fi
  pid=$2
  gcmd="$GEMSTONE/bin/pstackbrief.gdb"
else
  if [ $# -ne 1 ] ; then
    args="bad"
  fi
  pid=$1
  gcmd="$GEMSTONE/bin/pstack.gdb"
fi
if [ "$args" = "bad" ]; then
  echo "Usage: pstack <pid>"
  echo "       pstack -b <pid>"
  exit 1
fi
gdb=gdb
type $gdb
errcode=$?
if [ $errcode -ne 0 ] ; then
    echo "Cannot find $gdb in path $PATH"
    exit $errcode
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
# --command runs commands from the given file
echo "===--- start gdb stacks"
date
$gdb --nw --nx --batch --pid=$pid --command=$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"

