Tuesday, January 15, 2008

Quick and dirty stack dumps

So I had a situation where I didn't have root access but needed to get a stack trace of all the running threads in a daemon.

So I whipped up this little script, which I could just tell the sysadmin to run:

#!/bin/sh

if [ "$1" == "" -o "$2" == "" ]; then
echo "usage: get_stack.sh <program> <pid>"
exit 1
fi

if [ ! -e $1 ]; then
echo "<program> specified not found"
exit 1
fi

TARGET=$1
TARGETPID=$2
GDB=/usr/bin/gdb

# Temporary files
CMDFILE=/tmp/gdb.$$
STACKDUMP=/tmp/stack.$$

/bin/echo "set height 1000000" > $CMDFILE
/bin/echo "thread apply all bt" >> $CMDFILE
/bin/echo "quit" >> $CMDFILE
$GDB --command=$CMDFILE $TARGET $TARGETPID > $STACKDUMP
cat $STACKDUMP

# Cleanup
/bin/rm $CMDFILE
/bin/rm $STACKDUMP

It's not foolproof, but it is good enough for most situations and saves having to manually walk the user through a GDB session.