【发布时间】:2021-03-12 21:38:27
【问题描述】:
我必须打印 ELF 文件头。它包含的所有数据,就像运行 readelf -h hello.bin 时一样。该程序是用 C 语言编写的。这是我到目前为止所拥有的:
typedef struct elf64_hdr {
unsigned char e_ident[EI_NIDENT]; /* ELF "magic number" */
Elf64_Half e_type;
Elf64_Half e_machine;
Elf64_Word e_version;
Elf64_Addr e_entry; /* Entry point virtual address */
Elf64_Off e_phoff; /* Program header table file offset */
Elf64_Off e_shoff; /* Section header table file offset */
Elf64_Word e_flags;
Elf64_Half e_ehsize;
Elf64_Half e_phentsize;
Elf64_Half e_phnum;
Elf64_Half e_shentsize;
Elf64_Half e_shnum;
Elf64_Half e_shstrndx;
} Elf64_Ehdr;
typedef struct elf64_shdr {
Elf64_Word sh_name; /* Section name, index in string tbl */
Elf64_Word sh_type; /* Type of section */
Elf64_Xword sh_flags; /* Miscellaneous section attributes */
Elf64_Addr sh_addr; /* Section virtual addr at execution */
Elf64_Off sh_offset; /* Section file offset */
Elf64_Xword sh_size; /* Size of section in bytes */
Elf64_Word sh_link; /* Index of another section */
Elf64_Word sh_info; /* Additional section information */
Elf64_Xword sh_addralign; /* Section alignment */
Elf64_Xword sh_entsize; /* Entry size if section holds table */
} Elf64_Shdr;
这些是结构。 以下是 main 中声明的变量:
FILE* ElfFile = NULL;
char* SectNames = NULL;
Elf64_Ehdr elfHdr;
Elf64_Shdr sectHdr;
uint32_t idx;
这是打印代码的相关部分,需要您的帮助:
// read ELF header, first thing in the file
fread(&elfHdr, 1, sizeof(Elf64_Ehdr), ElfFile);
SectNames = malloc(sectHdr.sh_size); //variable for section names (like "Magic", "Data" etc.)
fseek(ElfFile, sectHdr.sh_offset, SEEK_SET); //going to the offset of the section
fread(SectNames, 1, sectHdr.sh_size, ElfFile); //reading the size of section
for(int i=0; i<sectHdr.sh_size; i++)
{
char *name1 = "";
fseek(ElfFile, elfHdr.e_shoff + i*sizeof(sectHdr), SEEK_SET);
fread(§Hdr, 1, sizeof(sectHdr), ElfFile);
name1 = SectNames + sectHdr.sh_name;
printf("%s \n", name1);
}
代码编译但不打印任何内容。我希望打印诸如“Magic”、“Data”、“Class”等字符串......
【问题讨论】:
-
SectNames = malloc(sectHdr.sh_size);读取sectHdr的代码此时尚未执行。如果这不是问题,请提供完整的代码minimal verifiable example -
虽然您当然推出了自己的版本,但有一个 ELF 库可以完成您想做的大部分工作:
libelf。您可以从您的发行版安装开发包。 (例如)在 Fedora 中,它是elfutils-libelf-devel
标签: c linux binaryfiles elf