从 elf/obj 文件中提取字符串变量

Col*_*olH 5 elf binutils

我试图从 Linux 程序的 elf 文件中提取特定的字符串变量(即符号),甚至从它来自的 .o 中提取。它在 .rodata 部分,显然我知道符号名称。是否有一系列 objdump 样式的命令和选项可用于转储字符串?

更新:

例如,.map 文件包括:

.rodata.default_environment 0x000000001013f763 0x615 common/built-in.o
                            0x000000001013f763    default_environment
Run Code Online (Sandbox Code Playgroud)

变量本身 - default_environment- 是标准的以空字符结尾的文本字符串。

Emp*_*ian 6

是否有一系列 objdump 样式的命令和选项可用于转储字符串?

当然。让我们构建一个例子:

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

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

$ gcc -c t.c
Run Code Online (Sandbox Code Playgroud)

假设我们要提取 的内容bar[]

$ readelf -Ws t.o | grep bar
    10: 000000000000000a    11 OBJECT  GLOBAL DEFAULT    5 bar
Run Code Online (Sandbox Code Playgroud)

这告诉我们bar变量的“内容”在第 5 部分的 offset 处0xa,长度为 11 个字节。

我们可以提取整个第 5 节:

$ readelf -x5 t.o

Hex dump of section '.rodata':
  0x00000000 536f6d65 20746578 74004f74 68657220 Some text.Other 
  0x00000010 74657874 00                         text.
Run Code Online (Sandbox Code Playgroud)

并确实找到了我们正在寻找的字符串。如果您真的只想提取的内容bar(例如,因为.rodata非常大,和/或因为bar包含嵌入的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
Run Code Online (Sandbox Code Playgroud)

看结果:

$ xd bar
000000   O   t   h   e   r       t   e   x   t nul                              O t h e r   t e x t . 
Run Code Online (Sandbox Code Playgroud)

QED。