本节书摘来自华章出版社《深入分析GCC 》一书中的第2章,第2.3节,作者 王亚刚 ,更多章节内容可以访问云栖社区“华章计算机”公众号查看。
2.3 GNU binutils工具
在分析GCC代码时,尤其是后端代码生成的过程中,经常需要对编译生成的目标文件进行分析,包括编译生成的汇编代码、目标文件等,此时,如果能够熟练使用GNU binutils工具链中的工具,无疑将对分析非常有用。GNU binutils工具的源代码及介绍参见GNU的官网:http://www.gnu.org/software/binutils/,其中主要工具如表2-1所示。

例如,对于如下的源代码:
[GCC@localhost test]$ cat test.c
int main(){
int i=0, sum=0;
sum = sum + i;
return sum;
}
可以使用objdump进行目标代码的反汇编:
[GCC@localhost test]$ gcc -c -o test.o test.c
[GCC@localhost test]$ objdump -d test.o
test.o: file format elf32-i386
Disassembly of section .text:
00000000 <main>:
0: 55 push %ebp
1: 89 e5 mov %esp,%ebp
3: 83 ec 10 sub $0x10,%esp
6: c7 45 f8 00 00 00 00 movl $0x0,-0x8(%ebp)
d: c7 45 fc 00 00 00 00 movl $0x0,-0x4(%ebp)
14: 8b 45 f8 mov -0x8(%ebp),%eax
17: 01 45 fc add %eax,-0x4(%ebp)
1a: 8b 45 fc mov -0x4(%ebp),%eax
1d: c9 leave
1e: c3 ret
可以使用nm查看目标文件中的符号信息:
[GCC@localhost test]$ nm test.o
00000000 T main
也可以使用readelf工具查看目标文件的ELF信息。
[GCC@localhost test]$ readelf -a test.o
ELF Header:
Magic: 7f 45 4c 46 01 01 01 00 00 00 00 00 00 00 00 00
Class: ELF32
Data: 2's complement, little endian
Version: 1 (current)
OS/ABI: UNIX - System V
ABI Version: 0
Type: REL (Relocatable file)
Machine: Intel 80386
Version: 0x1
Entry point address: 0x0
Start of program headers: 0 (bytes into file)
Start of section headers: 200 (bytes into file)
Flags: 0x0
Size of this header: 52 (bytes)
Size of program headers: 0 (bytes)
Number of program headers: 0
Size of section headers: 40 (bytes)
Number of section headers: 9
Section header string table index: 6
Section Headers:
[Nr] Name Type Addr Off Size ES Flg Lk Inf Al
[ 0] NULL 00000000 000000 000000 00 0 0 0
[ 1] .text PROGBITS 00000000 000034 00001f 00 AX 0 0 4
[ 2] .data PROGBITS 00000000 000054 000000 00 WA 0 0 4
[ 3] .bss NOBITS 00000000 000054 000000 00 WA 0 0 4
[ 4] .comment PROGBITS 00000000 000054 00002e 01 MS 0 0 1
[ 5] .note.GNU-stack PROGBITS 00000000 000082 000000 00 0 0 1
[ 6] .shstrtab STRTAB 00000000 000082 000045 00 0 0 1
[ 7] .symtab SYMTAB 00000000 000230 000080 10 8 7 4
[ 8] .strtab STRTAB 00000000 0002b0 00000d 00 0 0 1
Key to Flags:
W (write), A (alloc), X (execute), M (merge), S (strings)
I (info), L (link order), G (group), x (unknown)
O (extra OS processing required) o (OS specific), p (processor specific)
There are no section groups in this file.
There are no program headers in this file.
There are no relocations in this file.
There are no unwind sections in this file.
Symbol table '.symtab' contains 8 entries:
Num: Value Size Type Bind Vis Ndx Name
0: 00000000 0 NOTYPE LOCAL DEFAULT UND
1: 00000000 0 FILE LOCAL DEFAULT ABS test.c
2: 00000000 0 SECTION LOCAL DEFAULT 1
3: 00000000 0 SECTION LOCAL DEFAULT 2
4: 00000000 0 SECTION LOCAL DEFAULT 3
5: 00000000 0 SECTION LOCAL DEFAULT 5
6: 00000000 0 SECTION LOCAL DEFAULT 4
7: 00000000 31 FUNC GLOBAL DEFAULT 1 main
No version information found in this file.