#!/bin/ksh
#
# Function: 	Dump dbx information of pthread application
# Usage:    	./dbxpth <PID>
# Written by: 	taochen@austin.ibm.com
# Last update: 	12-20-2002

## Do we have a PID ?
if (( $# != 1 ))
then
        echo "Usage: dbxpth <PID>"
        return 1
fi

## Is it an existing PID ?
ps -p $1 > /dev/null 2>&1
if (( $? == 1 ))
then
        echo "PID $1 doesn't exist"
        return 1
fi

PID=$1
COMM="`ps -p $PID -ocomm=`"
OFILE="dbxpth.$COMM.$PID.`date +%d%h%Y-%H.%M.%S`.out"
> $OFILE

PID=$1

# System Information:
echo "CPU#:     $((`lsdev -Cc processor|wc -l`))"       >> $OFILE
BIT=$((`bootinfo -K`))
echo "Kernel:   $BIT-bit\n\n"                           >> $OFILE
lslpp -l bos.rte.libpthreads bos.rte.libc bos.mp bos.up \
2>/dev/null | grep bos                                  >> $OFILE


## 12/20/2002 Since dbx might kill the process, get the ps output first.
echo "\n"             >> $OFILE
ps -mo THREAD -p $PID >> $OFILE
echo "\n"             >> $OFILE
ps auxeww $PID        >> $OFILE
echo "\n"             >> $OFILE

# Instead of calling dbx each time, we build a command list (COMMS) 
# and send it to dbx at the end.

BRK='p "."'
DBX=">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"

echo "\nDumping threads and locks information ...\n"

COMMS="p '$DBX thread'\n$BRK\nthread\n$BRK\n"
COMMS=$COMMS"p '$DBX thread info'\n$BRK\n thread info\n$BRK\n"
COMMS=$COMMS"p '$DBX mutex      '\n$BRK\n mutex      \n$BRK\n"
COMMS=$COMMS"p '$DBX condition  '\n$BRK\n condition  \n$BRK\n"
COMMS=$COMMS"p '$DBX rwlock     '\n$BRK\n rwlock     \n$BRK\n" 

#### FIX on 12/20/2002:
#### Since thread number is not necessarily continuous,
#### we have to get the exact thread number.

for TPT in `echo "th \ndetach" | dbx -a $PID 2>&1 | egrep "^..t[0-9]"| awk '{print $1}'`
do
        PT=${TPT#*t}

#### End of FIX on 12/20/2002

	echo "thread $PT stack and registers ..."
	COMMS=$COMMS"p '$DBX thread current $PT' \n$BRK\n thread current $PT\n$BRK\n"
	COMMS=$COMMS"p '$DBX where $PT' \n$BRK\n where \n$BRK\n"
	COMMS=$COMMS"p '$DBX x $PT' \n$BRK\n x \n$BRK\n$BRK\n"

done
COMMS=$COMMS"p '$DBX map'\n$BRK\n map \ndetach"

echo "$COMMS" | dbx -a $PID 2>/dev/null >> $OFILE
echo "\nDone.\nOutput file is $OFILE\n"

## THE END
