Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract a string variable from elf/obj file

Tags:

elf

binutils

I'm trying to extract a particular string variable (i.e. symbol) from a Linux program's elf file, or even from the .o it comes from. It's in the .rodata section, and obviously I know the symbol name. Is there a sequence of objdump-style commands and options I can use to dump out the string?

Update:

For example, the .map file includes:

.rodata.default_environment 0x000000001013f763 0x615 common/built-in.o
                            0x000000001013f763    default_environment

The variable itself - default_environment - is a standard null-terminated text string.

like image 784
ColH Avatar asked Jul 21 '17 11:07

ColH


1 Answers

Is there a sequence of objdump-style commands and options I can use to dump out the string?

Sure. Let's construct an example:

const char foo[] = "Some text";
const char bar[] = "Other text";

const void *fn1() { return foo; }
const void *fn2() { return bar; }

$ gcc -c t.c

Suppose we want to extract contents of bar[].

$ readelf -Ws t.o | grep bar
    10: 000000000000000a    11 OBJECT  GLOBAL DEFAULT    5 bar

This tells us that the "contents" of the bar variable is in section 5, at offset 0xa, and is 11 bytes long.

We can extract the entire section 5:

$ readelf -x5 t.o

Hex dump of section '.rodata':
  0x00000000 536f6d65 20746578 74004f74 68657220 Some text.Other 
  0x00000010 74657874 00                         text.

and indeed find the string we are looking for. If you really want to extract just the contents of bar (e.g. because the .rodata is really large, and/or because bar contains embedded NULs):

$ objcopy -j.rodata -O binary t.o t.rodata    # extract just .rodata section
$ dd if=t.rodata of=bar bs=1 skip=10 count=11 # extract just bar

11+0 records in
11+0 records out
11 bytes (11 B) copied, 0.000214501 s, 51.3 kB/s

Look at result:

$ xd bar
000000   O   t   h   e   r       t   e   x   t nul                              O t h e r   t e x t . 

QED.

like image 177
Employed Russian Avatar answered Nov 28 '22 17:11

Employed Russian