Skip to content

Instantly share code, notes, and snippets.

@uobikiemukot
Last active August 29, 2015 14:03
Show Gist options
  • Save uobikiemukot/a36192db130f86951460 to your computer and use it in GitHub Desktop.
Save uobikiemukot/a36192db130f86951460 to your computer and use it in GitHub Desktop.
catch segmentation fault and show wrong lines in source code
#!/bin/bash
# usage: cdebug.sh ./a.out
# (remember to add "-rdynamic" and "-g" option to gcc!)
# example: gcc -O0 -g -rdynamic foo.c && cdebug.sh ./a.out
if test "$#" -lt 1; then
echo "usage: cdebug.sh ./a.out"
echo "(remember to add '-rdynamic' and '-g' option to gcc!)"
echo "example: gcc -O0 -g -rdynamic foo.c && cdebug.sh ./a.out"
exit 1
fi
# set filename
EXECFILE=$1
# RANGE value for sed 'p'
RANGE=2
# set env and exec
export LD_PRELOAD=/usr/lib/libSegFault.so
export SEGFAULT_USE_ALTSTACK=1
export SEGFAULT_SIGNALS=all
ADDR=`eval $EXECFILE 2>&1 | grep "${EXECFILE}.*\[.*\]" | egrep -o "\[0x[0-9a-z]+\]" | head -1 | tr -d "]["`
echo segfault at $EXECFILE $ADDR
# find wrong line in source code
SRCFILE=`addr2line -e $EXECFILE $ADDR | cut -d: -f1`
LINE=`addr2line -e $EXECFILE $ADDR | cut -d: -f2`
MAXLINE=`wc -l $SRCFILE | cut -d" " -f1`
#echo line: $LINE
# show error code
FROM=`expr $LINE - $RANGE`
TO=`expr $LINE + $RANGE`
if test $FROM -lt 1; then
FROM=1
fi
if test $TO -gt $MAXLINE; then
TO=$MAXLINE
fi
#echo from: $FROM to: $TO maxline: $MAXLINE
echo $SRCFILE:$LINE
nl -ba $SRCFILE | sed -n "${FROM},${TO}p"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment