我有一个C程序,我想在其中打印出输入文件的节头的名称。我根据研究ELF表示法制作了所有内容,并帮助了Internet上的现有程序,但仍然无法正常工作。它仅打印来自for循环的索引,该索引也应为节名称。有人看到我想念的东西吗?
代码:
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <elf.h>
int main(int argc, char *argv[]) {
int fd;
int val;
Elf32_Ehdr elfHdr;
Elf32_Shdr sectHdr;
FILE* ElfFile = NULL;
char* SectNames = NULL;
if(argc != 2) {
perror("Error while opening file");
return 0;
}
ElfFile = fopen(argv[1], "r");
if(ElfFile == NULL) {
printf("fopen");
return -1;
}
//preberemo elf header
fread(&elfHdr, 1, sizeof(Elf64_Ehdr), ElfFile);
printf("\tVersion: 0x%.2X\n", elfHdr.e_version);
printf("\tEntry point address: 0x%.8X\n", elfHdr.e_entry);
printf("\tProgram header offset: 0x%.8X\n", elfHdr.e_phoff);
printf("\tSection header offset: 0x%.8X\n", elfHdr.e_shoff);
printf("\tFlags: 0x%.8X\n", elfHdr.e_flags);
printf("\tSize of this header: 0x%X\n", elfHdr.e_ehsize);
printf("\tSize of program headers: 0x%X\n", elfHdr.e_phentsize);
printf("\tNumber of program headers: %d\n", elfHdr.e_phnum);
printf("\tSize of section headers: 0x%X\n", elfHdr.e_shentsize);
printf("\tNumber of section headers: %d\n", elfHdr.e_shnum);
printf("\tSection header string table index: 0x%X\n", elfHdr.e_shstrndx);
//premik do section tabele
fseek(ElfFile, elfHdr.e_shoff + elfHdr.e_shstrndx * elfHdr.e_shentsize, SEEK_SET);
fread(§Hdr, 1, sizeof(sectHdr), ElfFile);
SectNames = malloc(sectHdr.sh_size);
fseek(ElfFile, sectHdr.sh_offset, SEEK_SET);
fread(SectNames, 1, sectHdr.sh_size, ElfFile);
for (int idx = 0; idx < elfHdr.e_shnum; idx++){
char* name = "";
fseek(ElfFile, elfHdr.e_shoff + idx * sizeof(sectHdr), SEEK_SET);
fread(§Hdr, 1, sizeof(sectHdr), ElfFile);
// print section name
if (sectHdr.sh_name);
name = SectNames + sectHdr.sh_name;
printf("%i %s\n", idx, name);
}
close(fd);
return 0;
}
有人看到我错过的东西吗?
您是否以32位模式编译程序?
它对我有用:
gcc -w -m32 t.c && ./a.out ./a.out
Version: 0x01
Entry point address: 0x000010C0
Program header offset: 0x00000034
Section header offset: 0x000038B0
Flags: 0x00000000
Size of this header: 0x34
Size of program headers: 0x20
Number of program headers: 11
Size of section headers: 0x28
Number of section headers: 30
Section header string table index: 0x1D
0
1 .interp
2 .note.gnu.build-id
3 .note.ABI-tag
4 .gnu.hash
5 .dynsym
6 .dynstr
7 .gnu.version
8 .gnu.version_r
9 .rel.dyn
10 .rel.plt
11 .init
12 .plt
13 .plt.got
14 .text
15 .fini
16 .rodata
17 .eh_frame_hdr
18 .eh_frame
19 .init_array
20 .fini_array
21 .dynamic
22 .got
23 .got.plt
24 .data
25 .bss
26 .comment
27 .symtab
28 .strtab
29 .shstrtab
[如果要在64位ELF文件上运行它,则需要用等效的Elf32_Ehdr
更改Elf32_Shdr
和Elf64_...
。