我有一个 C 程序,我想在其中打印输入文件的节标题的名称。
我所做的一切都是基于研究 ELF 表示法,并帮助解决了互联网上现有的程序,但它仍然不起作用。它只打印 for 循环中的索引,其中也应该是节名称。有人看到我错过的东西吗?
更新:
我更新了代码并删除了导致堆栈溢出的错误(如果将来有人需要它)。
Code:
#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(Elf32_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;
}