Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extracting only my function names from ELF binary

Im writing a script for extracting all the functions(written by user) in a binary.

The following shell script extracts my function names as well as some library functions which starts with __

readelf -s ./a.out | gawk '
{ 
  if($4 == "FUNC" && $3 != "0" && $7 == "13" && $8 != "main") { 
    print "b " $NF; //***Updated
  } 
}' &> function_names; 

Output of function_names file:

b __libc_csu_fini
b PrintDivider    
b PrintFooter    
b __libc_csu_init    
b PrintHeader

I would like to extract only my function. so how to check whether function name starts with __ or else any other alternatives also highly appriciated.

Update::
@djf solution works fine. What if .c files which are compiled also may contain a function which starts with __? In that case, how to differentiate?

like image 565
Jeyaram Avatar asked Dec 06 '22 06:12

Jeyaram


2 Answers

What about using readelf on your object file(s) instead of the linked executable? Then there's no spam from the library functions. Use the -c flag to compile to an object file and not link immediately.

PS: The proper tool to extract names from an executable or object file is nm, not readelf. Using nm -P file has everything you want.

$ nm -P tst.o | awk '$2 == "T" {print "b " $1}'
b foo
b main

EDIT: To ignore main and symbols starting with an underscore, use

$ nm -P a.out | awk '$2 == "T" && $1 !~ /^_/ && $1 != "main" {print "b " $1}'
like image 61
Jens Avatar answered Dec 08 '22 21:12

Jens


You could add a regex check to make sure that the function name starts with a letter.

I presume that $8 contains the function name:

readelf -s ./a.out | gawk '
{
  if($4 == "FUNC" && $3 != "0" && $7 == "13" && $8 != "main" && $8~/^[[:alpha:]]/) {
    print $NF;
  }
}'
like image 24
djf Avatar answered Dec 08 '22 21:12

djf