#!/bin/sh

# Based on the Red Hat gdb rpm's "gdb/gstack.sh" script.
# It is not clear what the original license of this little script was.
#
# Modified by Tall Maple Systems, 2010, to print backtrace symbols.

if test $# -ne 1; then
    echo "Usage: `basename $0 .sh` <process-id>" 1>&2
    exit 1
fi

if test ! -r /proc/$1; then
    echo "Process $1 not found." 1>&2
    exit 1
fi

# GDB doesn't allow "thread apply all bt" when the process isn't
# threaded; need to peek at the process to determine if that or the
# simpler "bt" should be used.

backtrace="bt"
if test -d /proc/$1/task ; then
    # Newer kernel; has a task/ directory.
    if test `/bin/ls /proc/$1/task | /usr/bin/wc -l` -gt 1 2>/dev/null ; then
        backtrace="thread apply all bt"
    fi
elif test -f /proc/$1/maps ; then
    # Older kernel; go by it loading libpthread.
    if /bin/grep -e libpthread /proc/$1/maps > /dev/null 2>&1 ; then
        backtrace="thread apply all bt"
    fi
fi

GDB=${GDB:-/usr/bin/gdb}

## if $GDB -nx --quiet --batch --readnow > /dev/null 2>&1; then
##     readnow=--readnow
## else
##     readnow=
## fi

# Run GDB, strip out unwanted noise.
$GDB --quiet $readnow -nx /proc/$1/exe $1 <<EOF 2>&1 |
$backtrace
EOF
/bin/sed  \
    -e 's/^(gdb) //' |
/bin/awk 'BEGIN { state=0 }
    /^.*#0 /    { state=1 }
    /^Thread /  { state=1 }
    {
        if ( state > 0 ) {
           if (! /^Thread/ && /^[^# \t]/) {
                exit
           }
           if (! /^$/) {
                print;
           }
        }
    }'
