Search code examples
linuxshared-librariessymbolselfnm

How to extract symbols and see their offset in the file


I can extract symbols using the "nm -a -D" command.
But is there a way to extract the symbol names with an offset from the start of the file?

For example,

nm -D ./libc.so

Shows me this -

...
00000000000f8c60 T xdr_wrapstring
00000000000f7cc0 T xencrypt
00000000000bd230 T __xmknod
00000000000bd2a0 T __xmknodat
000000000003ec70 T __xpg_basename
00000000000314b0 W __xpg_sigpause
0000000000080db0 T __xpg_strerror_r
00000000000f6090 T xprt_register
00000000000f61f0 T xprt_unregister
00000000000bd110 T __xstat
00000000000bd110 T __xstat64

Now, I want to get the offset of the symbol names from the start of the file in the same way that the "strings -t x" command shows the offset of the strings -

strings -t x ./libc.so | grep __xstat
  13af9 __xstat
  13fac __xstat64

How can I do this?

(I can't use the "strings" command on the output of the "nm" command because there could be multiple instances of the same symbol string in the file and I want to get the exact offset of the symbol (not just some string that is the same as the symbol))


Solution

  • But is there a way to extract the symbol names with an offset from the start of the file?

    There sure is: nm is doing it (in order to print the names).

    You should be aware that there could be two symbol tables: a regular one and a dynamic one (nm -D displays the latter).

    The symbols themselves are stored in .dynsym section (or .symtab section for the regular symbol table), and they contain the offset into .dynstr section (which actually contains the names).

    So adding ".dynstr".sh_offset + "symbol".st_name will give you offset of the symbol name in the file.

    Sample code here. (The code uses .symtab and .strtab; you'll need to adjust it to use .dynsym and .dynstr to print the dynamic symbol table.)