下面的代码可以列出节标题名称。
int main()
{
const char *file_name;
char *strtable, *sh_name;
size_t file_size;
struct stat st;
void *data;
Elf64_Ehdr hdr;
Elf64_Shdr shdr;
int i, fd, idx, strndx, stroff, spot;
if ((fd = open(file_name, O_RDONLY)) < 0) {
printf("fail to open %s\n", file_name);
exit(EXIT_FAILURE);
}
data = MAP_FAILED;
if (!fstat(fd, &st)) {
file_size = st.st_size;
data = mmap(0, file_size, PROT_READ, MAP_PRIVATE, fd, 0);
}
close(fd);
if (data == MAP_FAILED) {
printf("Unable map\n");
exit(EXIT_FAILURE);
}
// read elf header
memcpy(&hdr, data, sizeof(hdr));
// read section header string table header
spot = hdr.e_shoff; // section header table file offset
strndx = hdr.e_shstrndx; // section header string table index
stroff = spot + strndx * hdr.e_shentsize;
memcpy(&shdr, (char *)data + stroff, hdr.e_shentsize);
// read section string table
strtable = (char *)malloc(shdr.sh_size);
memcpy(strtable, (char *)data + shdr.sh_offset, shdr.sh_size);
for (i = 0; i< hdr.e_shnum; ++i) {
memcpy(&shdr, (char *)data + spot, hdr.e_shentsize);
spot += hdr.e_shentsize;
sh_name = &(strtable[shdr.sh_name]);
printf("[%d] %s\n", i, sh_name);
}
}
结果如下:
[0]
[1] .interp
[2] .note.ABI-tag
[3] .gnu.hash
[4] .dynsym
[5] .dynstr
[6] .gnu.version
...