#!/bin/sh

version=$(uname -r)
vmlinux=/lib/modules/$version/source/vmlinux
tmpFile=/tmp/vmlinux-`date +%Y%m%d%H%M%S`

# Read function name from command-line
myFunction="$1"
if [ -z $myFunction ]; then
   echo "Please enter function name"
   echo "Usage: $0 <function_name>
        E.g $0 rtc_cmos_read"
   exit 1
fi

# Output file is created in current working directory
assemblyText=$myFunction.asm

# Delete existing file
rm -f $assemblyText

# Verify that vmlinux exists
if [ ! -e $vmlinux ]; then 
   echo "vmlinux binary not found at $vmlinux"
   exit 1
fi

# Dump contents of objdump to a temporary file
objdump -d $vmlinux > $tmpFile

# Obtain line number where our function starts
count=$(grep -n "<$myFunction>:"  $tmpFile | cut -f 1 -d ':')

# Exit if function source not found
if [ -z $count ]; then
   echo "Unable to find source for function $myFunction in $vmlinux"
   exit 1
fi

echo -e "Assembly for function $myFunction(), Linux kernel version $version\n" >> $assemblyText
# Extract source for $myFunction from $tmpFile
while [ 1 ]; 
do 
   line=$(head -$count $tmpFile | tail -1)
   # Exit when blank line is encountered
   if [ "x$line" == "x" ]; then
      # Delete temporary file
      rm -f $tmpFile
      # Echo blank line to $assemblyText
      echo "$line" >> $assemblyText
      echo "Assembly for $myFunction written to file $assemblyText"
      exit 0
   else
      echo "$line" >> $assemblyText
   fi
   count=$(($count+1))
done

