2

I am trying to find the location of myfunc in the executable of:

#include <stdio.h>

void myfunc(){
    printf("Hello");
}

int main(){

}

I wrote this script:

#!/bin/bash -x
start=$(nm -S a.out|grep -w _start)
start_addr=$(echo $start | awk '{print $1}')
myfun=$(nm -S a.out|grep $1)
myfun_addr=$(echo $myfun | awk '{print $1}')
myfun_length=$(echo $myfun | awk '{print $2}')
echo $myfun_length
myfun_end=$(echo "obase=16;ibase=16;$myfun_addr + $myfun_length" | bc)
offset=$(echo "obase=16;ibase=16;$myfun_addr - $start_addr" | bc)

The last line runs, but the line before it no:

++ echo 'obase=16;ibase=16;0000000000400900 + 00000000000000bc'
++ bc
(standard_in) 1: syntax error
+ myfun_end=
++ echo 'obase=16;ibase=16;0000000000400900 - 0000000000400710'
++ bc
+ offset=1F0
robert
  • 3,539
  • 3
  • 35
  • 56
  • I really want to know the reason of the downvote. This is the first time I use `bc`. The two lines looks almost the same, both have valid variables. Many environments accept both upper- and lowercase hex numbers. So please, explain why you voted this question down. – robert Dec 03 '15 at 12:51
  • Just a guess for downvote: no C involved in either the question or possible answers. – pmg Dec 03 '15 at 12:53
  • Unlike other Stackexchange sites, here are some really bitchy users. – robert Dec 03 '15 at 12:54

2 Answers2

6

Hexadecimal numbers in bc are represented with UPPERCASE letters.

Try adding tr to some pipe

... | tr "a-z" "A-Z" | ...

Do not use IBASE and OBASE, these need to be lowercase.

pmg
  • 106,608
  • 13
  • 126
  • 198
4

You don't need to use bc. You can specify hexadecimal values for the standard $((...)) expression, then use printf to output in hexadecimal.

start=$(nm -S a.out | grep -w _start)
start_addr=${start%% *}   # Shorter, more efficient
myfun=$(nm -S a.out | grep "$1")
read myfun_addr myfun_length rest <<< "$myfun"  # Shorter, more efficient
echo $myfun_length
myfun_end=$(( 0x$myfun_addr + 0x$myfun_length ))
printf -v offset "%x" $(( 0x$myfun_addr - 0x$start_addr" ))
chepner
  • 497,756
  • 71
  • 530
  • 681