Skip to content

Detecting a specific segfault

Johannes Pfau edited this page Jul 13, 2013 · 2 revisions

###Bash (Linux/Posix only) Note: This script expects a core dump to be written to a core file. See ulimit for more information.

#!/bin/sh
BINARY="test" #the binary to test
SEGFUNC="_aaDelX" #the function where the segfault occurs (as in the gdb backtrace!)
dmd test.d -of$BINARY 2>/dev/null #Your compile command

echo $(sh -c "./$BINARY" 2>&1) | grep -q "Segmentation fault" #Make sure there was a segfault
if [ $? -eq 0 ]
then
    gdb --batch -ex 'backtrace' $BINARY core 2>&1 | grep -q "#0 .* in $SEGFUNC"
    if [ $? -eq 0 ]
    then
        return 0
    else
        return 1
    fi
else
    return 1
fi

If grep -q "Segmentation fault" doesn't work for you it's also possible to check the return value of ./$BINARY 2>&1 which should return 139 in case of a segfault.

###Bash (alternative without core files)

#!/bin/sh
BINARY="test" #the generated binary to test
SEGFUNC="D main ()" #the function where the segfault occurs (as in the gdb backtrace!)
dmd test.d -of$BINARY 2>/dev/null #Your compile command

OUTPUT=$(gdb --batch -ex 'run' -ex 'backtrace' ./$BINARY 2>&1)
echo "$OUTPUT" | grep -q "Program received signal SIGSEGV, Segmentation fault." #Make sure there was a segfault
if [ $? -eq 0 ]
then
    echo "$OUTPUT" | grep "#0"| grep -q " in $SEGFUNC"
    if [ $? -eq 0 ]
    then
        return 0
    else
        return 1
    fi
else
    return 1
fi