#!/bin/sh

DATABASES="*.dat support/*.dat"
DATABASES="AAA.dat"
SIGNATURESIZE=100
RELEVANT=80

if [ $# -lt 2 ]
then
	echo "usage: $0 <address to check in databases> <binary file> <function name>"
	exit 1
fi
type objdump >/dev/null 2>&1
if [ $? -ne 0 ]
then
	echo I need objdump command in your PATH
	exit 1
fi
type afprint2 >/dev/null 2>&1
if [ $? -ne 0 ]
then
	type ./afprint2 >/dev/null 2>&1
	if [ $? -ne 0 ]
	then
		echo I need afprint2 executable to be in your PATH
		exit 1
	else
		AFPRINT=./afprint2
	fi
else
	AFPRINT=afprint2
fi

FPRINT=`objdump -d --start-address $1 $2 2>/dev/null| tail +8 | cut -c10- | cut -c-23 | $AFPRINT`
echo ""
if [ $# -lt 3 ]
then
echo Fingerprint for address $1 is $FPRINT
else
echo Fingerprint for address $1 [$3] is $FPRINT
fi
echo "Searching in databases for a similar ($RELEVANT%) function... (this can take a while)"
echo ""

for D in $DATABASES
do
{
NF=`wc -l $D|awk '{print $1}'`
let N=1
while [ $N -le $NF ]
do
	CMATCH=1
	read LINE
	FNAME=`echo $LINE|cut -d' ' -f2`
	SIG=`echo $LINE|cut -d' ' -f3-`
	NMATCHED=0
	echo -ne "                                                        \r"
	echo -ne "$D: [$N/$NF] Testing $FNAME...\r"
	while [ $CMATCH -le $SIGNATURESIZE ]
	do
		C1=`echo $FPRINT|cut -d' ' -f$CMATCH`
		C2=`echo $SIG|cut -d' ' -f$CMATCH`
		if [ "$C1" = "$C2" ]
		then
			let NMATCHED=NMATCHED+1
		fi
			let CMATCH=CMATCH+1
	done
	if [ $NMATCHED -ge $RELEVANT ]
	then
		echo "$FNAME matched with ${NMATCHED}%                         "
		let RESULT=RESULT+1
	fi
	let N=N+1
done
} < $D
done
if [ $RESULT -eq 0 ]
then
	echo No match found.
else
	echo "$RESULT possible matches found with correlation > $RELEVANT%."
fi
echo ""
exit 0
