#!/bin/bash

out=/tmp/OS-5444-hotpatch.$$

let already=0
let patched=0

echo "cmntrap::dis" | mdb -k | grep cmpl | grep rbp | grep -w 0x0 > /dev/null

if [[ $? -eq 0 ]]; then
	echo "`uname -v` seems to have fix for OS-5444"
	exit 0
fi

echo "dtrace_dif_emulate::dis" | mdb -k | grep idiv | cut -d: -f1 > $out

if [[ `wc -l $out | awk '{ print $1 }'` != "2" ]]; then
	echo "unexpected number of idiv instructions in dtrace_dif_emulate"
	rm $out
	exit 1
fi

for inst in `cat $out`; do
	i=`echo $inst-2/x | mdb -k | awk '{ print $2 }'`

	if [[ "$i" -eq "d231" ]]; then
		let already=already+1
	else
		if [[ "$i" -ne "9948" ]]; then
			echo "unrecognized instruction at $inst!"
			rm $out
			exit 1
		fi

		echo $inst-2/w d231 | mdb -kw > /dev/null 2>&1 
		let patched=patched+1
	fi
done

rval=`dtrace -n BEGIN'{v = -10LL; printf("%d", v / 2); exit(0)}' -q`

if [[ "$rval" -ne "9223372036854775803" ]]; then
	echo "patched $patched instructions ($already already patched)," \
	    "unexpected return $rval!"
	rm $out
	exit 1
fi

echo "patched $patched instructions ($already already patched)"
rm $out
